// Shared UI for Apex Learn Toastmasters, in the BECoach visual language.
// Tokens (--font-rounded, --space-*, --radius-*, --ease-*) come from becoach-tokens.css;
// palette tokens (--ink, --surface, --accent, --gold …) are theme-driven in app.jsx.

const PILLAR_COLORS = ["#FFB3BA", "#88D8F4", "#A8E6CF", "#66BF8C"];

// The signature four-circle Venn mandala, repurposed as the club's growth pillars.
function Mandala({ size = 240, labels, center, animate = true, showLabels = true }) {
  const r = size * 0.22;
  const offset = size * 0.14;
  const cx = size / 2, cy = size / 2;
  const pillars = [
    { cx, cy: cy - offset, color: PILLAR_COLORS[0], at: [cx, cy - offset - r - size * 0.05] },
    { cx: cx + offset, cy, color: PILLAR_COLORS[1], at: [cx + offset + r + size * 0.055, cy] },
    { cx, cy: cy + offset, color: PILLAR_COLORS[2], at: [cx, cy + offset + r + size * 0.07] },
    { cx: cx - offset, cy, color: PILLAR_COLORS[3], at: [cx - offset - r - size * 0.055, cy] },
  ];
  const uid = React.useId();
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}
         style={{ overflow: "visible", animation: animate ? "mandala-breath 7s ease-in-out infinite alternate" : undefined }}>
      <defs>
        <radialGradient id={`core-${uid}`} cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="#FFEAA7" />
          <stop offset="100%" stopColor="#FDCB6E" />
        </radialGradient>
        <filter id={`blur-${uid}`}><feGaussianBlur stdDeviation="0.4" /></filter>
      </defs>
      {pillars.map((p, i) => (
        <circle key={i} cx={p.cx} cy={p.cy} r={r} fill={p.color} fillOpacity="0.55"
                stroke={p.color} strokeOpacity="0.9" strokeWidth="1.5"
                style={{ mixBlendMode: "screen" }} filter={`url(#blur-${uid})`} />
      ))}
      <circle cx={cx} cy={cy} r={size * 0.092} fill={`url(#core-${uid})`}
              style={{ filter: "drop-shadow(0 0 14px rgba(253,203,110,0.6))" }} />
      {center && (
        <text x={cx} y={cy} textAnchor="middle" dominantBaseline="central"
              fontFamily="var(--font-serif)" fontSize={size * 0.072} fontWeight="600" fill="#3a2a08">
          {center}
        </text>
      )}
      {showLabels && labels && labels.map((l, i) => (
        <text key={"l" + i} x={pillars[i].at[0]} y={pillars[i].at[1]}
              textAnchor="middle" dominantBaseline="middle"
              fontFamily="var(--font-rounded)" fontSize={size * 0.058} fontWeight="600"
              fill="rgba(255,255,255,0.9)" letterSpacing="0.04em">
          {l}
        </text>
      ))}
    </svg>
  );
}

// Small mandala glyph used as the logo mark (no labels).
function LogoMark({ size = 40 }) {
  const r = size * 0.26;
  const off = size * 0.17;
  const c = size / 2;
  const uid = React.useId();
  const pts = [[c, c - off], [c + off, c], [c, c + off], [c - off, c]];
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} aria-hidden="true">
      <defs>
        <radialGradient id={`lcore-${uid}`} cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="#FFEAA7" /><stop offset="100%" stopColor="#FDCB6E" />
        </radialGradient>
      </defs>
      {pts.map((p, i) => (
        <circle key={i} cx={p[0]} cy={p[1]} r={r} fill={PILLAR_COLORS[i]} fillOpacity="0.5"
                stroke={PILLAR_COLORS[i]} strokeOpacity="0.9" strokeWidth="1" style={{ mixBlendMode: "screen" }} />
      ))}
      <circle cx={c} cy={c} r={size * 0.12} fill={`url(#lcore-${uid})`}
              style={{ filter: "drop-shadow(0 0 5px rgba(253,203,110,0.7))" }} />
    </svg>
  );
}

function Wordmark({ c, onClick }) {
  return (
    <div onClick={onClick} style={{ display: "flex", alignItems: "center", gap: 13, cursor: "pointer" }}>
      <LogoMark size={40} />
      <div style={{ display: "flex", flexDirection: "column", gap: 3, lineHeight: 1.1 }}>
        <span style={{ fontFamily: "var(--font-rounded)", fontSize: 18, fontWeight: 700, color: "var(--ink)", letterSpacing: "0.01em", whiteSpace: "nowrap", lineHeight: 1.1 }}>
          {c.club.name}
        </span>
        <span style={{ fontFamily: "var(--font-rounded)", fontSize: 10, fontWeight: 600, color: "var(--gold)", letterSpacing: "0.22em", textTransform: "uppercase", whiteSpace: "nowrap", lineHeight: 1.2 }}>
          {c.club.tagline}
        </span>
      </div>
    </div>
  );
}

function Button({ children, onClick, variant = "solid", size = "md", type = "button" }) {
  const [hover, setHover] = React.useState(false);
  const [press, setPress] = React.useState(false);
  const pad = size === "lg" ? "0 28px" : "0 20px";
  const h = size === "lg" ? 56 : 46;
  const fs = size === "lg" ? 17 : 14.5;
  const base = {
    height: h, padding: pad, fontFamily: "var(--font-rounded)", fontWeight: 600, fontSize: fs,
    borderRadius: "var(--radius-md)", cursor: "pointer", border: "1px solid transparent",
    display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8, whiteSpace: "nowrap",
    transition: "transform var(--dur-quick) var(--ease-spring-quick), filter var(--dur-quick) ease",
    transform: press ? "scale(0.97)" : hover ? "translateY(-1px)" : "none",

  };
  const variants = {
    solid: { background: "var(--accent-grad)", color: "var(--on-accent)", border: "1.5px solid rgba(255,255,255,0.18)", boxShadow: hover ? "var(--glow)" : "none", filter: hover ? "brightness(1.04)" : "none" },
    outline: { background: "var(--surface)", color: "var(--ink)", border: "1px solid var(--surface-border)" },
    ghost: { background: "transparent", color: "var(--ink-soft)", border: "1px solid transparent" },
  };
  return (
    <button type={type} onClick={onClick}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => { setHover(false); setPress(false); }}
      onMouseDown={() => setPress(true)} onMouseUp={() => setPress(false)}
      style={{ ...base, ...variants[variant] }}>
      {children}
    </button>
  );
}

function Kicker({ children }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 18 }}>
      <span style={{ width: 22, height: 2, borderRadius: 2, background: "var(--accent-grad)" }} />
      <span style={{ fontFamily: "var(--font-rounded)", fontSize: 12, fontWeight: 600, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--gold)", whiteSpace: "nowrap" }}>
        {children}
      </span>
    </div>
  );
}

function Badge({ children }) {
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "8px 15px", borderRadius: "var(--radius-full)", background: "var(--panel)", border: "1px solid var(--surface-border)", color: "var(--ink-soft)", fontFamily: "var(--font-rounded)", fontSize: 12.5, fontWeight: 600, whiteSpace: "nowrap" }}>
      <span style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--accent)", boxShadow: "var(--glow)", flexShrink: 0 }} />
      {children}
    </div>
  );
}

// Glass surface card.
function GlassCard({ children, style = {}, pad = 30, radius = "var(--radius-xl)" }) {
  return (
    <div style={{ background: "var(--surface)", border: "1px solid var(--surface-border)", borderRadius: radius, padding: pad, boxShadow: "var(--card-shadow)", ...style }}>
      {children}
    </div>
  );
}

function ImagePlaceholder({ label, ratio = "4 / 3", radius = "var(--radius-xl)" }) {
  return (
    <div style={{ aspectRatio: ratio, width: "100%", borderRadius: radius, border: "1px dashed var(--surface-border)", background: "var(--panel)", display: "flex", alignItems: "center", justifyContent: "center", overflow: "hidden" }}>
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 10, color: "var(--ink-faint)", padding: 16, textAlign: "center" }}>
        <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
          <rect x="3" y="3" width="18" height="18" rx="3" />
          <circle cx="8.5" cy="8.5" r="1.8" />
          <path d="M21 15l-5-5L5 21" />
        </svg>
        <span style={{ fontFamily: "var(--font-rounded)", fontSize: 12, letterSpacing: "0.04em", fontWeight: 500 }}>{label}</span>
      </div>
    </div>
  );
}

// Drifting blurred particles — the BECoach cosmic background field.
function ParticleField() {
  const parts = React.useMemo(() =>
    Array.from({ length: 12 }, () => ({
      left: Math.random() * 100,
      size: 2 + Math.random() * 5,
      delay: -Math.random() * 16,
      dur: 14 + Math.random() * 12,
      drift: (Math.random() - 0.5) * 40,
      op: 0.2 + Math.random() * 0.5,
    })), []);
  return (
    <div aria-hidden="true" style={{ position: "fixed", inset: 0, overflow: "hidden", pointerEvents: "none", zIndex: 0 }}>
      {parts.map((p, i) => (
        <span key={i} style={{
          position: "absolute", bottom: "-8%", left: `${p.left}%`,
          width: p.size, height: p.size, borderRadius: "50%",
          background: "var(--particle)", opacity: p.op,
          ["--drift"]: `${p.drift}px`,
          animation: `particle-rise ${p.dur}s linear ${p.delay}s infinite`,
        }} />
      ))}
    </div>
  );
}

function Header({ c, route, go, toggleLang }) {
  const items = [["home", c.nav.home], ["about", c.nav.about], ["meetings", c.nav.meetings], ["join", c.nav.join], ["assistant", c.nav.assistant]];
  return (
    <header style={{ position: "sticky", top: 0, zIndex: 50, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 20, padding: "14px clamp(20px, 5vw, 56px)", background: "color-mix(in oklab, var(--bg-solid) 70%, transparent)", backdropFilter: "blur(18px) saturate(160%)", WebkitBackdropFilter: "blur(18px) saturate(160%)", borderBottom: "1px solid var(--surface-border)" }}>
      <Wordmark c={c} onClick={() => go("home")} />
      <nav style={{ display: "flex", alignItems: "center", gap: 2 }} className="apex-nav">
        {items.map(([key, label]) => (
          <button key={key} onClick={() => go(key)} style={{ fontFamily: "var(--font-rounded)", fontSize: 14.5, fontWeight: route === key ? 700 : 500, color: route === key ? "var(--ink)" : "var(--ink-soft)", background: route === key ? "var(--surface)" : "transparent", border: "1px solid " + (route === key ? "var(--surface-border)" : "transparent"), cursor: "pointer", padding: "9px 15px", borderRadius: "var(--radius-full)", whiteSpace: "nowrap", transition: "color var(--dur-quick) ease" }}>
            {label}
          </button>
        ))}
      </nav>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <button onClick={toggleLang} title="切换语言 / Switch language" style={{ fontFamily: "var(--font-rounded)", fontSize: 13, fontWeight: 700, color: "var(--ink)", background: "var(--surface)", border: "1px solid var(--surface-border)", borderRadius: "var(--radius-full)", padding: "9px 15px", cursor: "pointer", display: "flex", alignItems: "center", gap: 7 }}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3c2.5 2.7 2.5 15.3 0 18M12 3c-2.5 2.7-2.5 15.3 0 18" /></svg>
          {c.altLangName}
        </button>
        <span className="apex-cta-head"><Button onClick={() => go("join")}>{c.nav.cta}</Button></span>
      </div>
    </header>
  );
}

function Footer({ c, go }) {
  const items = [["home", c.nav.home], ["about", c.nav.about], ["meetings", c.nav.meetings], ["join", c.nav.join], ["assistant", c.nav.assistant]];
  const head = { fontFamily: "var(--font-rounded)", fontSize: 11.5, fontWeight: 700, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--gold)", marginBottom: 16 };
  return (
    <footer style={{ borderTop: "1px solid var(--surface-border)", padding: "56px clamp(20px, 5vw, 56px) 36px", position: "relative", zIndex: 1 }}>
      <div style={{ maxWidth: 1180, margin: "0 auto", display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr", gap: 40 }} className="apex-foot-grid">
        <div>
          <Wordmark c={c} onClick={() => go("home")} />
          <p style={{ fontFamily: "var(--font-serif)", fontSize: 18, color: "var(--ink-soft)", marginTop: 20, maxWidth: 320, lineHeight: 1.55 }}>{c.footer.tagline}</p>
        </div>
        <div>
          <div style={head}>{c.footer.nav}</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {items.map(([key, label]) => (
              <button key={key} onClick={() => go(key)} style={{ textAlign: "left", fontFamily: "var(--font-rounded)", fontSize: 14.5, color: "var(--ink-soft)", background: "none", border: "none", cursor: "pointer", padding: 0 }}>{label}</button>
            ))}
          </div>
        </div>
        <div>
          <div style={head}>{c.footer.contact}</div>
          <a href={"mailto:" + c.contact.email} style={{ fontFamily: "var(--font-rounded)", fontSize: 14.5, color: "var(--ink-soft)", textDecoration: "none", display: "block", marginBottom: 10 }}>{c.contact.email}</a>
          <div style={{ fontFamily: "var(--font-rounded)", fontSize: 14.5, color: "var(--ink-soft)", marginBottom: 10 }}>{c.contact.loc}</div>
          <div style={{ fontFamily: "var(--font-rounded)", fontSize: 14.5, color: "var(--ink-soft)" }}>toastmasters.apexlearn.org</div>
        </div>
      </div>
      <div style={{ maxWidth: 1180, margin: "40px auto 0", paddingTop: 24, borderTop: "1px solid var(--surface-border)", display: "flex", flexWrap: "wrap", gap: 12, justifyContent: "space-between" }}>
        <span style={{ fontFamily: "var(--font-rounded)", fontSize: 12.5, color: "var(--ink-faint)" }}>© 2026 {c.footer.built}</span>
        <span style={{ fontFamily: "var(--font-rounded)", fontSize: 12.5, color: "var(--ink-faint)", maxWidth: 560, lineHeight: 1.5 }}>{c.footer.legal}</span>
      </div>
    </footer>
  );
}

Object.assign(window, { Mandala, LogoMark, Wordmark, Button, Kicker, Badge, GlassCard, ImagePlaceholder, ParticleField, Header, Footer });
