// Shared UI atoms for Lucy AI

// Lucy logo mark — a literary "L" with serif terminals
function LucyMark({ size = 32, accent = "#C8A84B", textColor = "#0B0F19" }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: "50%",
      background: `radial-gradient(circle at 30% 25%, ${accent}, color-mix(in oklab, ${accent} 65%, #000))`,
      display: "flex", alignItems: "center", justifyContent: "center",
      boxShadow: `0 0 0 1px ${accent}33, 0 8px 24px ${accent}30`,
      flexShrink: 0,
    }}>
      <span style={{
        fontFamily: FONTS.fraunces,
        fontWeight: 600, fontSize: size * 0.56, color: textColor,
        lineHeight: 1, marginTop: -size * 0.02,
        fontVariationSettings: '"opsz" 144, "SOFT" 50',
      }}>L</span>
    </div>
  );
}

// Header — appears across screens
function LucyHeader({ T, t, lang, setLang, theme, setTheme, onRestart, accent, showBack, onBack, step }) {
  return (
    <div style={{
      display: "flex", alignItems: "center", justifyContent: "space-between",
      padding: "0 16px", height: 52,
      borderBottom: `1px solid ${T.border}`,
      background: theme === "dark" ? "rgba(11,15,25,0.65)" : "rgba(245,241,232,0.7)",
      backdropFilter: "blur(20px) saturate(180%)",
      WebkitBackdropFilter: "blur(20px) saturate(180%)",
      flexShrink: 0,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        {showBack ? (
          <button onClick={onBack} style={{
            border: "none", background: "transparent", cursor: "pointer",
            width: 32, height: 32, borderRadius: 8,
            display: "flex", alignItems: "center", justifyContent: "center",
            color: T.textDim,
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M9 2L4 7l5 5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        ) : (
          <LucyMark size={28} accent={accent.primary} textColor={theme === "dark" ? "#0B0F19" : "#0B0F19"} />
        )}
        {!showBack && (
          <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
            <span style={{ fontFamily: FONTS.fraunces, fontWeight: 500, fontSize: 19, color: T.text, letterSpacing: -0.3 }}>Lucy</span>
            <span style={{
              fontFamily: FONTS.ui, fontSize: 9, fontWeight: 700, letterSpacing: 0.8,
              color: accent.primary, padding: "2px 6px", borderRadius: 3,
              background: accent.primarySoft, border: `1px solid ${accent.primary}40`,
            }}>PRO</span>
          </div>
        )}
        {step && (
          <span style={{ fontFamily: FONTS.ui, fontSize: 11, color: T.textMute, marginLeft: 6, fontVariantNumeric: "tabular-nums" }}>
            {step}
          </span>
        )}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
        {/* Language toggle */}
        <div style={{
          display: "flex", padding: 2, borderRadius: 999,
          background: T.surfaceStrong, border: `1px solid ${T.border}`,
        }}>
          {["VN", "EN"].map(L => (
            <button key={L} onClick={() => setLang(L.toLowerCase())} style={{
              fontFamily: FONTS.ui, fontSize: 10.5, fontWeight: 600,
              padding: "4px 9px", border: "none", cursor: "pointer",
              borderRadius: 999, letterSpacing: 0.4,
              background: lang === L.toLowerCase() ? accent.primary : "transparent",
              color: lang === L.toLowerCase() ? "#0B0F19" : T.textDim,
              transition: "all 200ms ease",
            }}>{L}</button>
          ))}
        </div>
        {/* Theme toggle */}
        <button onClick={() => setTheme(theme === "dark" ? "light" : "dark")} style={{
          width: 32, height: 32, borderRadius: 999, border: "none",
          background: "transparent", cursor: "pointer",
          display: "flex", alignItems: "center", justifyContent: "center",
          color: T.textDim,
        }}>
          {theme === "dark" ? (
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M11.5 8.5A4.5 4.5 0 016.5 3.5a5 5 0 105 5z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"/>
            </svg>
          ) : (
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <circle cx="7" cy="7" r="2.8" stroke="currentColor" strokeWidth="1.3"/>
              {[0,45,90,135,180,225,270,315].map(d => {
                const r = d * Math.PI / 180;
                const x1 = 7 + Math.cos(r) * 4.5, y1 = 7 + Math.sin(r) * 4.5;
                const x2 = 7 + Math.cos(r) * 6.2, y2 = 7 + Math.sin(r) * 6.2;
                return <line key={d} x1={x1} y1={y1} x2={x2} y2={y2} stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
              })}
            </svg>
          )}
        </button>
        {onRestart && (
          <button onClick={onRestart} style={{
            fontFamily: FONTS.ui, fontSize: 10.5, color: T.textMute,
            border: "none", background: "transparent", cursor: "pointer", padding: "4px 6px",
          }}>{t.restart}</button>
        )}
      </div>
    </div>
  );
}

// Editorial kicker line — small caps tracking
function Kicker({ children, T, accent }) {
  return (
    <div style={{
      display: "flex", alignItems: "center", gap: 8,
      fontFamily: FONTS.ui, fontSize: 10, fontWeight: 600,
      letterSpacing: 1.6, textTransform: "uppercase",
      color: accent.primary,
    }}>
      <span style={{ width: 18, height: 1, background: accent.primary, opacity: 0.6 }} />
      {children}
    </div>
  );
}

// Section title — Fraunces serif, multi-line
function SerifTitle({ children, T, size = 38, font = FONTS.fraunces }) {
  return (
    <h1 style={{
      fontFamily: font, fontWeight: 400, fontSize: size,
      lineHeight: 1.02, letterSpacing: -0.8, color: T.text,
      margin: 0, fontVariationSettings: '"opsz" 144, "SOFT" 50',
      whiteSpace: "pre-line",
    }}>{children}</h1>
  );
}

// Body text
function Body({ children, T, dim = true, size = 13.5, style = {} }) {
  return <p style={{
    fontFamily: FONTS.ui, fontSize: size, lineHeight: 1.55,
    color: dim ? T.textDim : T.text, margin: 0, ...style,
  }}>{children}</p>;
}

// Primary CTA
function PrimaryButton({ children, onClick, accent, disabled, T }) {
  const [hover, setHover] = React.useState(false);
  const [active, setActive] = React.useState(false);

  return (
    <button 
      onClick={onClick} 
      disabled={disabled}
      onMouseEnter={() => !disabled && setHover(true)}
      onMouseLeave={() => { setHover(false); setActive(false); }}
      onMouseDown={() => !disabled && setActive(true)}
      onMouseUp={() => setActive(false)}
      style={{
        width: "100%", height: 52, border: "none",
        borderRadius: 12, cursor: disabled ? "not-allowed" : "pointer",
        background: disabled ? T.surfaceStrong : (active ? `color-mix(in oklab, ${accent.primary} 85%, #000)` : (hover ? `color-mix(in oklab, ${accent.primary} 92%, #fff)` : accent.primary)),
        color: disabled ? T.textMute : "#0B0F19",
        fontFamily: FONTS.ui, fontSize: 15, fontWeight: 600, letterSpacing: -0.1,
        boxShadow: disabled ? "none" : (active ? `0 4px 12px ${accent.primaryGlow}` : (hover ? `0 12px 32px ${accent.primaryGlow}` : `0 8px 24px ${accent.primaryGlow}, inset 0 1px 0 rgba(255,255,255,0.25)`)),
        transform: active ? "scale(0.975)" : (hover ? "scale(1.01)" : "scale(1)"),
        transition: "all 120ms cubic-bezier(0.2, 0.8, 0.2, 1)",
        display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
      }}>
      {children}
      {!disabled && <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ transition: "transform 150ms", transform: hover ? "translateX(2px)" : "none" }}><path d="M3 7h8m0 0L7 3m4 4L7 11" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>}
    </button>
  );
}

// Outlined secondary — accent border, transparent fill
function SecondaryButton({ children, onClick, accent, T, style = {} }) {
  const [hover, setHover] = React.useState(false);
  const [active, setActive] = React.useState(false);

  return (
    <button 
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => { setHover(false); setActive(false); }}
      onMouseDown={() => setActive(true)}
      onMouseUp={() => setActive(false)}
      style={{
        width: "100%", height: 50, border: `1px solid ${accent.primary}`,
        borderRadius: 12, cursor: "pointer",
        background: active ? `${accent.primary}15` : (hover ? `${accent.primary}08` : "transparent"),
        color: accent.primary, fontFamily: FONTS.ui, fontSize: 14, fontWeight: 600, letterSpacing: 0.2,
        display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
        transform: active ? "scale(0.98)" : "scale(1)",
        transition: "all 150ms ease",
        ...style,
      }}>{children}</button>
  );
}

// Ghost / secondary
function GhostButton({ children, onClick, T, style = {} }) {
  const [hover, setHover] = React.useState(false);
  const [active, setActive] = React.useState(false);

  return (
    <button 
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => { setHover(false); setActive(false); }}
      onMouseDown={() => setActive(true)}
      onMouseUp={() => setActive(false)}
      style={{
        width: "100%", height: 48, border: `1px solid ${active ? T.borderStrong : T.border}`,
        borderRadius: 12, cursor: "pointer", 
        background: active ? T.surfaceStrong : (hover ? T.surface : "transparent"),
        color: T.text, fontFamily: FONTS.ui, fontSize: 14, fontWeight: 500,
        transform: active ? "scale(0.98)" : "scale(1)",
        transition: "all 150ms ease",
        ...style,
      }}>{children}</button>
  );
}

// Ambient glow background — gold + secondary accent halos
function AmbientBg({ T, accent, theme, variant = "default" }) {
  return (
    <div aria-hidden style={{
      position: "absolute", inset: 0, overflow: "hidden", pointerEvents: "none", zIndex: 0,
    }}>
      <div style={{
        position: "absolute", left: -100, top: -120, width: 320, height: 480, borderRadius: "50%",
        background: accent.primary,
        opacity: theme === "dark" ? 0.18 : 0.13,
        filter: "blur(80px)",
      }} />
      <div style={{
        position: "absolute", right: -120, top: 200, width: 280, height: 400, borderRadius: "50%",
        background: accent.chart[1],
        opacity: theme === "dark" ? 0.12 : 0.08,
        filter: "blur(80px)",
      }} />
      {variant === "report" && (
        <div style={{
          position: "absolute", right: -80, bottom: 100, width: 320, height: 320, borderRadius: "50%",
          background: accent.chart[2],
          opacity: theme === "dark" ? 0.1 : 0.07,
          filter: "blur(90px)",
        }} />
      )}
    </div>
  );
}

// Lucy "intelligence orb" — abstract gradient sphere with rotating glints
function LucyOrb({ size = 180, accent, theme, processing = false }) {
  return (
    <div style={{
      width: size, height: size, position: "relative", flexShrink: 0,
    }}>
      {/* outer halo ring */}
      <div style={{
        position: "absolute", inset: -8, borderRadius: "50%",
        border: `1px solid ${accent.primary}30`,
        boxShadow: `0 0 60px ${accent.primaryGlow}`,
      }} />
      {/* sphere */}
      <div style={{
        position: "absolute", inset: 0, borderRadius: "50%",
        background: `radial-gradient(circle at 32% 28%, ${accent.primary}EE 0%, ${accent.primary}80 22%, ${accent.chart[2]}60 55%, ${theme === "dark" ? "#0B0F19" : "#1a1f2e"} 90%)`,
        boxShadow: `inset -10px -16px 40px rgba(0,0,0,0.4), inset 8px 8px 20px ${accent.primary}40`,
        overflow: "hidden",
      }}>
        {/* rotating shimmer */}
        <div style={{
          position: "absolute", inset: -20, borderRadius: "50%",
          background: `conic-gradient(from 0deg, transparent 0%, ${accent.primary}30 25%, transparent 50%, ${accent.chart[1]}30 75%, transparent 100%)`,
          animation: `${processing ? "lucyOrbSpin 4s linear infinite" : "lucyOrbSpin 18s linear infinite"}`,
          mixBlendMode: "screen",
        }} />
        {/* glint */}
        <div style={{
          position: "absolute", left: "22%", top: "20%", width: "28%", height: "22%", borderRadius: "50%",
          background: "radial-gradient(circle, rgba(255,255,255,0.6) 0%, transparent 70%)",
          filter: "blur(4px)",
        }} />
      </div>
      {/* concentric tick marks */}
      <svg width={size + 60} height={size + 60} viewBox={`0 0 ${size+60} ${size+60}`} style={{ position: "absolute", inset: -30, animation: processing ? "lucyOrbSpin 12s linear infinite" : "none" }}>
        {Array.from({length: 60}).map((_, i) => {
          const a = (i / 60) * 2 * Math.PI;
          const r1 = size/2 + 18, r2 = size/2 + 22;
          const cx = (size+60)/2, cy = (size+60)/2;
          return <line key={i}
            x1={cx + Math.cos(a) * r1} y1={cy + Math.sin(a) * r1}
            x2={cx + Math.cos(a) * r2} y2={cy + Math.sin(a) * r2}
            stroke={accent.primary} strokeOpacity={i % 5 === 0 ? 0.5 : 0.18} strokeWidth={i % 5 === 0 ? 1 : 0.5}
          />;
        })}
      </svg>
    </div>
  );
}

// Floating-label text input
function FloatingInput({ label, value, onChange, placeholder, T, accent, type = "text", error }) {
  const [focused, setFocused] = React.useState(false);
  const float = focused || value;
  return (
    <div style={{ position: "relative" }}>
      <div style={{
        position: "relative",
        borderRadius: 12,
        background: T.surface,
        border: `1px solid ${error ? "#A66B5C" : focused ? accent.primary : T.border}`,
        transition: "border-color 150ms",
        height: 60,
      }}>
        <label style={{
          position: "absolute", left: 14, top: float ? 8 : 20,
          fontFamily: FONTS.ui, fontSize: float ? 10 : 14,
          color: focused ? accent.primary : T.textMute,
          letterSpacing: float ? 1 : 0,
          textTransform: float ? "uppercase" : "none",
          fontWeight: float ? 600 : 400,
          pointerEvents: "none",
          transition: "all 180ms cubic-bezier(0.2, 0.8, 0.2, 1)",
        }}>{label}</label>
        <input
          type={type}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          placeholder={float ? placeholder : ""}
          style={{
            width: "100%", height: "100%",
            background: "transparent", border: "none", outline: "none",
            fontFamily: FONTS.ui, fontSize: 15, color: T.text,
            padding: "26px 14px 8px", boxSizing: "border-box",
          }}
        />
      </div>
    </div>
  );
}

Object.assign(window, {
  LucyMark, LucyHeader, Kicker, SerifTitle, Body,
  PrimaryButton, SecondaryButton, GhostButton, AmbientBg, LucyOrb, FloatingInput,
});
