// =============================================================
// Xiaomo site — primitive components
// =============================================================
const { useState, useEffect, useMemo, useRef } = React;

const Motif = ({ name, size = 24, style = {} }) => (
  <img src={`../assets/motifs/${name}.svg`} alt="" style={{ width: size, height: size, display: "inline-block", ...style }} />
);

const Button = ({ variant = "primary", size = "md", icon, onClick, children, type = "button", style = {}, disabled }) => {
  const variants = {
    primary:   { background: "#B8852E", color: "#FFFDF6", boxShadow: "0 4px 16px rgba(184,133,46,0.30), inset 0 1px 0 rgba(255,255,255,0.35)" },
    secondary: { background: "#FFF1D4", color: "#8B4F32", boxShadow: "inset 0 0 0 1px rgba(217,162,86,0.5)" },
    ghost:     { background: "transparent", color: "#6B4A2E", boxShadow: "inset 0 0 0 2px #FBE3B0" },
    mint:      { background: "#B5E5CF", color: "#2D6B4F", boxShadow: "0 4px 14px rgba(111,203,160,0.3)" },
    cream:     { background: "#FBEFC2", color: "#6B4A2E", boxShadow: "inset 0 0 0 1px #ECDDC0" },
  };
  const sizes = { sm: { padding: "7px 14px", fontSize: 13 }, md: { padding: "11px 20px", fontSize: 15 }, lg: { padding: "14px 26px", fontSize: 17 } };
  return (
    <button type={type} onClick={onClick} disabled={disabled}
      style={{
        fontFamily: "'Jiangcheng Yuan', 'PingFang SC', sans-serif",
        border: "none", cursor: disabled ? "not-allowed" : "pointer",
        display: "inline-flex", alignItems: "center", gap: 6,
        borderRadius: 999, letterSpacing: "0.04em",
        opacity: disabled ? 0.5 : 1,
        transition: "transform 200ms cubic-bezier(0.34,1.56,0.64,1), box-shadow 200ms",
        ...sizes[size], ...variants[variant], ...style,
      }}
      onMouseEnter={(e) => !disabled && (e.currentTarget.style.transform = "scale(1.05)")}
      onMouseLeave={(e) => (e.currentTarget.style.transform = "scale(1)")}
      onMouseDown={(e) => !disabled && (e.currentTarget.style.transform = "scale(0.96)")}
      onMouseUp={(e) => !disabled && (e.currentTarget.style.transform = "scale(1.05)")}>
      {icon}{children}
    </button>
  );
};

const Chip = ({ tone = "pink", children, onClick, style = {} }) => {
  const tones = {
    pink:  { background: "#FFF1D4", color: "#8B4F32" },
    mint:  { background: "#CCEDDB", color: "#2D6B4F" },
    blue:  { background: "#C8DEEC", color: "#5A99BD" },
    cream: { background: "#FBEFC2", color: "#6B4A2E", border: "1px dashed #D6BD9A" },
    solid: { background: "#B8852E", color: "#FFFDF6", boxShadow: "0 2px 8px rgba(184,133,46,0.26)" },
    gold:  { background: "linear-gradient(135deg,#FFE89E,#FFD27A)", color: "#6B4A2E", boxShadow: "0 2px 6px rgba(255,210,122,0.4)" },
  };
  return (
    <span onClick={onClick} style={{
      fontFamily: "'Jiangcheng Yuan', 'PingFang SC', sans-serif", fontSize: 12,
      padding: "4px 12px", borderRadius: 999, display: "inline-flex", alignItems: "center", gap: 6,
      letterSpacing: "0.04em", cursor: onClick ? "pointer" : "default",
      ...tones[tone], ...style,
    }}>{children}</span>
  );
};

const Card = ({ children, tinted = false, dashed = false, gold = false, style = {}, onClick }) => (
  <div onClick={onClick} style={{
    background: dashed ? "#FFFDF6" : tinted ? "linear-gradient(180deg,#FFF1D4,#FFFDF6)" : "#FFFDF6",
    borderRadius: 20, padding: 18,
    boxShadow: dashed ? "none" : gold
      ? "0 4px 20px rgba(255,210,122,0.3), inset 0 0 0 2px #FFD27A, inset 0 0 0 1px rgba(255,255,255,0.6)"
      : "0 4px 20px rgba(217,162,86,0.24), inset 0 0 0 1px rgba(255,255,255,0.6)",
    border: dashed ? "2px dashed #FBE3B0" : "none",
    position: "relative", overflow: "hidden",
    cursor: onClick ? "pointer" : "default",
    transition: "transform 200ms cubic-bezier(0.34,1.56,0.64,1), box-shadow 200ms",
    ...style,
  }}
  onMouseEnter={onClick ? (e) => { e.currentTarget.style.transform = "translateY(-2px)"; } : undefined}
  onMouseLeave={onClick ? (e) => { e.currentTarget.style.transform = "translateY(0)"; } : undefined}
  >{children}</div>
);

const Field = ({ label, value, onChange, placeholder, multiline = false, type = "text", style = {} }) => {
  const [focused, setFocused] = useState(false);
  const base = {
    fontFamily: "'Jiangcheng Yuan', 'PingFang SC', sans-serif", fontSize: 15, color: "#4A2A1A",
    background: "#FFFDF6",
    border: focused ? "2px solid #B8852E" : "2px solid #FBE3B0",
    borderRadius: 16, padding: "11px 16px", outline: "none", width: "100%", boxSizing: "border-box",
    boxShadow: focused ? "inset 0 0 0 1px rgba(255,255,255,0.6), 0 0 0 4px rgba(184,133,46,0.18)" : "inset 0 0 0 1px rgba(255,255,255,0.6)",
    transition: "all 200ms",
  };
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 6, ...style }}>
      {label && <span style={{ fontFamily: "'Jiangcheng Yuan', 'PingFang SC', sans-serif", fontSize: 13, color: "#6B4A2E", letterSpacing: "0.04em" }}>{label}</span>}
      {multiline
        ? <textarea value={value} onChange={onChange} placeholder={placeholder}
            onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}
            style={{ ...base, minHeight: 90, resize: "vertical", lineHeight: 1.7 }}/>
        : <input type={type} value={value} onChange={onChange} placeholder={placeholder}
            onFocus={() => setFocused(true)} onBlur={() => setFocused(false)} style={base}/>
      }
    </label>
  );
};

const Toast = ({ tone = "success", children }) => {
  const tones = {
    success: { background: "#E4F5EC", color: "#2D6B4F" },
    warn:    { background: "#FFF1D4", color: "#8B4F32" },
    cream:   { background: "#FFFDF6", color: "#4A2A1A" },
  };
  return <div style={{
    display: "inline-flex", alignItems: "center", gap: 10, padding: "12px 20px",
    borderRadius: 18, boxShadow: "0 8px 24px rgba(184,133,46,0.22), inset 0 0 0 1px rgba(255,255,255,0.7)",
    fontFamily: "'Jiangcheng Yuan', 'PingFang SC', sans-serif", fontSize: 14, ...tones[tone],
  }}>{children}</div>;
};

const Modal = ({ open, onClose, children, title, wide = false }) => {
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, zIndex: 200,
      background: "rgba(251,227,176,0.45)", backdropFilter: "blur(12px)", WebkitBackdropFilter: "blur(12px)",
      display: "flex", alignItems: "center", justifyContent: "center", padding: 20,
      animation: "fadeIn 200ms ease-out",
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: "100%", maxWidth: wide ? 720 : 480,
        maxHeight: "90vh", overflowY: "auto",
        background: "rgba(255,252,248,0.98)", borderRadius: 28,
        padding: "26px 26px 28px",
        boxShadow: "0 30px 80px rgba(184,133,46,0.26), inset 0 0 0 1px rgba(255,255,255,0.7)",
        animation: "popIn 320ms cubic-bezier(0.34,1.56,0.64,1)",
      }}>
        {title && <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
          <h3 style={{ font: "600 22px/1.2 'Jiangcheng Yuan', 'PingFang SC', sans-serif", margin: 0, color: "#4A2A1A", letterSpacing: "0.04em" }}>{title}</h3>
          <button onClick={onClose} style={{
            width: 36, height: 36, borderRadius: 999, border: "none", cursor: "pointer",
            background: "#FBEFC2", color: "#8B6B43", fontSize: 18, fontFamily: "Quicksand, sans-serif",
          }}>×</button>
        </div>}
        {children}
      </div>
    </div>
  );
};

// Section header — used across pages
const SectionHeader = ({ title, sub, action }) => (
  <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginBottom: 14 }}>
    <div>
      <h2 style={{ font: "600 24px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A", margin: 0, letterSpacing: "0.04em" }}>{title}</h2>
      {sub && <div style={{ font: "500 11px 'Quicksand', sans-serif", color: "#B5946D", letterSpacing: "0.1em", textTransform: "uppercase", marginTop: 2 }}>{sub}</div>}
    </div>
    {action}
  </div>
);

// Empty state
const Empty = ({ motif = "cloud", text, sub, action }) => (
  <div style={{ display: "flex", flexDirection: "column", alignItems: "center", padding: "40px 20px", textAlign: "center", gap: 10 }}>
    <Motif name={motif} size={72} style={{ opacity: 0.7 }}/>
    <div style={{ font: "600 16px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#6B4A2E", letterSpacing: "0.04em" }}>{text}</div>
    {sub && <div style={{ font: "400 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#B5946D" }}>{sub}</div>}
    {action}
  </div>
);

// Loading — spinning heart
const Loading = ({ text = "正在悄悄准备……" }) => (
  <div style={{ display: "flex", flexDirection: "column", alignItems: "center", padding: 40, gap: 10 }}>
    <Motif name="heart" size={36} style={{ animation: "xm-spin 1.4s linear infinite" }}/>
    <div style={{ font: "400 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#8B6B43" }}>{text}</div>
    <style>{`@keyframes xm-spin { to { transform: rotate(360deg) } }`}</style>
  </div>
);

// Confetti / heart-burst
const ConfettiBurst = ({ trigger }) => {
  const [bursts, setBursts] = useState([]);
  useEffect(() => {
    if (!trigger) return;
    const id = Math.random();
    const pieces = Array.from({ length: 24 }, (_, i) => ({
      i, motif: ["heart", "sakura", "star", "ribbon", "strawberry"][i % 5],
      x: 50 + (Math.random() - 0.5) * 10,
      tx: (Math.random() - 0.5) * 600,
      ty: -200 - Math.random() * 220,
      r: (Math.random() - 0.5) * 720,
      d: Math.random() * 0.2,
      s: 18 + Math.random() * 22,
    }));
    setBursts((b) => [...b, { id, pieces }]);
    setTimeout(() => setBursts((b) => b.filter(x => x.id !== id)), 2000);
  }, [trigger]);

  return (
    <>
      {bursts.map(b => (
        <div key={b.id} style={{ position: "fixed", left: 0, top: "60%", width: "100%", height: 0, pointerEvents: "none", zIndex: 300 }}>
          {b.pieces.map(p => (
            <img key={p.i} src={`../assets/motifs/${p.motif}.svg`} alt=""
              style={{
                position: "absolute", left: `${p.x}%`, width: p.s, height: p.s,
                animation: `confetti-fly 1800ms cubic-bezier(0.2,0.8,0.4,1) ${p.d}s forwards`,
                "--tx": p.tx + "px", "--ty": p.ty + "px", "--r": p.r + "deg",
              }}/>
          ))}
        </div>
      ))}
      <style>{`
        @keyframes confetti-fly {
          0%   { transform: translate(0,0) rotate(0); opacity: 1 }
          15%  { transform: translate(calc(var(--tx) * 0.3), var(--ty)) rotate(calc(var(--r) * 0.3)); opacity: 1 }
          100% { transform: translate(var(--tx), 200px) rotate(var(--r)); opacity: 0 }
        }
      `}</style>
    </>
  );
};

// Floating background motifs
const FloatingMotifs = () => (
  <div aria-hidden style={{ position: "fixed", inset: 0, pointerEvents: "none", overflow: "hidden", zIndex: 0 }}>
    {[
      { motif: "heart",      top: "8%",  left: "4%",  size: 32, delay: 0,   op: 0.14 },
      { motif: "sakura",     top: "22%", right: "6%", size: 42, delay: 1.5, op: 0.18 },
      { motif: "star",       top: "48%", left: "2%",  size: 26, delay: 3,   op: 0.14 },
      { motif: "cloud",      top: "60%", right: "4%", size: 50, delay: 2,   op: 0.16 },
      { motif: "ribbon",     top: "82%", left: "8%",  size: 36, delay: 4,   op: 0.16 },
      { motif: "strawberry", top: "90%", right: "10%",size: 30, delay: 1,   op: 0.16 },
    ].map((m, i) => (
      <img key={i} src={`../assets/motifs/${m.motif}.svg`} alt="" style={{
        position: "absolute", top: m.top, left: m.left, right: m.right,
        width: m.size, height: m.size, opacity: m.op,
        animation: `xm-float ${7 + (i % 3)}s ease-in-out ${m.delay}s infinite alternate`,
      }}/>
    ))}
    <style>{`@keyframes xm-float { 0%,100% { transform: translateY(0) rotate(-3deg) } 50% { transform: translateY(-10px) rotate(3deg) } }`}</style>
  </div>
);

Object.assign(window, { Motif, Button, Chip, Card, Field, Toast, Modal, SectionHeader, Empty, Loading, ConfettiBurst, FloatingMotifs });
