// Palette sets
const PALETTES = {
  cyan:   { sky: "oklch(0.86 0.09 220)",  skyDeep: "oklch(0.72 0.12 225)", accent: "oklch(0.60 0.19 25)",  accentInk: "oklch(0.48 0.18 25)", pop: "oklch(0.55 0.18 295)" },
  sunset: { sky: "oklch(0.88 0.08 70)",   skyDeep: "oklch(0.75 0.12 40)",  accent: "oklch(0.52 0.18 340)", accentInk: "oklch(0.42 0.18 340)", pop: "oklch(0.55 0.18 240)" },
  acid:   { sky: "oklch(0.90 0.12 130)",  skyDeep: "oklch(0.78 0.16 135)", accent: "oklch(0.45 0.18 290)", accentInk: "oklch(0.35 0.18 290)", pop: "oklch(0.60 0.19 25)"  },
  mono:   { sky: "oklch(0.94 0.005 250)", skyDeep: "oklch(0.85 0.01 250)", accent: "oklch(0.25 0.02 250)", accentInk: "oklch(0.18 0.02 250)", pop: "oklch(0.55 0.02 250)" },
};

const DISPLAY_FONTS = {
  "rubik-mono":   { family: "'Rubik Mono One', 'Arial Black', sans-serif", weight: 400, letterSpacing: "0.01em", skew: -2 },
  "marker":       { family: "'Rubik Marker Hatch', 'Marker Felt', sans-serif", weight: 400, letterSpacing: "0.02em", skew: -3 },
  "shrikhand":    { family: "'Shrikhand', 'Georgia', serif", weight: 400, letterSpacing: "0.00em", skew: -2 },
};

const getPalette = (t) => PALETTES[t.palette] || PALETTES.cyan;
const getFont    = (t) => DISPLAY_FONTS[t.displayFont] || DISPLAY_FONTS["rubik-mono"];

// The big hand-drawn wordmark
const Wordmark = ({ tweaks }) => {
  const p = getPalette(tweaks);
  const f = getFont(tweaks);
  // Display "AI GARAGE" big, "WEEKLY" as smaller banner underneath
  return (
    <div style={{ position: 'relative', textAlign: 'center', padding: '0 20px' }}>
      <h1 style={{
        margin: 0,
        fontFamily: f.family,
        fontWeight: f.weight,
        letterSpacing: f.letterSpacing,
        fontSize: 'clamp(48px, 9.2vw, 144px)',
        lineHeight: 0.88,
        color: p.accent,
        textShadow: `3px 3px 0 var(--ink), -1px -1px 0 var(--ink), 1px -1px 0 var(--ink), -1px 1px 0 var(--ink), 1px 1px 0 var(--ink)`,
        transform: `skewY(${f.skew}deg) rotate(-1.5deg)`,
        WebkitTextStroke: '1px var(--ink)',
        paintOrder: 'stroke fill',
      }}>
        AI GARAGE
      </h1>
      <div style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: 0,
        marginTop: 0,
        transform: 'rotate(0.8deg)',
      }}>
        <span style={{
          fontFamily: f.family,
          fontWeight: f.weight,
          letterSpacing: f.letterSpacing,
          fontSize: 'clamp(46px, 8.8vw, 138px)',
          lineHeight: 0.9,
          color: p.accent,
          textShadow: `3px 3px 0 var(--ink), -1px -1px 0 var(--ink), 1px -1px 0 var(--ink), -1px 1px 0 var(--ink), 1px 1px 0 var(--ink)`,
          transform: `skewY(${f.skew}deg) rotate(-1deg)`,
          WebkitTextStroke: '1px var(--ink)',
          paintOrder: 'stroke fill',
          display: 'inline-block',
          textTransform: 'uppercase',
        }}>WEEKLY</span>
      </div>
    </div>
  );
};

// Scattered doodles across the hero canvas
const DoodleField = ({ tweaks }) => {
  const p = getPalette(tweaks);
  const density = tweaks.doodleDensity || 'medium';
  const d = density === 'calm' ? 0.5 : density === 'busy' ? 1.3 : 1.0;

  // Positions as %; scale up count with density
  const base = [
    { kind: 'robot', x: 6,  y: 18, s: 72, r: -10 },
    { kind: 'robot', x: 86, y: 62, s: 64, r: 8 },
    { kind: 'robot', x: 48, y: 78, s: 56, r: -6, optional: true },
    { kind: 'crab',  x: 18, y: 72, s: 60, r: 6 },
    { kind: 'crab',  x: 78, y: 14, s: 88, r: -14 },
    { kind: 'crab',  x: 36, y: 30, s: 44, r: 18, optional: true },
    { kind: 'block', x: 2,  y: 60, s: 130, r: -18, fill: p.skyDeep, label: 'CHAIN' },
    { kind: 'block', x: 30, y: 4,  s: 100, r: -6,  fill: p.accent,  label: 'BLOCK', optional: true },
    { kind: 'block', x: 60, y: 90, s: 120, r: 6,   fill: p.skyDeep, label: 'NODE',  optional: true },
    { kind: 'coin',  x: 14, y: 40, s: 32 },
    { kind: 'coin',  x: 92, y: 42, s: 28 },
    { kind: 'coin',  x: 40, y: 60, s: 24, optional: true },
    { kind: 'sparkle', x: 25, y: 12, s: 18 },
    { kind: 'sparkle', x: 68, y: 4,  s: 22 },
    { kind: 'sparkle', x: 10, y: 84, s: 16 },
    { kind: 'sparkle', x: 95, y: 86, s: 20 },
    { kind: 'sparkle', x: 52, y: 22, s: 14 },
    { kind: 'star',    x: 44, y: 50, s: 10 },
    { kind: 'star',    x: 82, y: 82, s: 12 },
    { kind: 'star',    x: 8,  y: 8,  s: 14 },
  ];

  const items = base.filter(b => !b.optional || density !== 'calm')
                    .filter(b => density !== 'busy' ? true : true);

  // Add a few extra sparkles in "busy"
  const extras = density === 'busy' ? [
    { kind: 'sparkle', x: 30, y: 88, s: 14 },
    { kind: 'sparkle', x: 62, y: 70, s: 12 },
    { kind: 'star',    x: 72, y: 46, s: 10 },
    { kind: 'crab',    x: 56, y: 8, s: 40, r: 22 },
  ] : [];

  const all = [...items, ...extras];

  const render = (it, i) => {
    const animMap = {
      robot:   'doodle-bob',
      crab:    'doodle-scuttle',
      block:   'doodle-float',
      coin:    'doodle-spin',
      sparkle: 'doodle-twinkle',
      star:    'doodle-pulse',
    };
    const durMap = { robot: 3.2, crab: 2.8, block: 5.5, coin: 4.8, sparkle: 2.2, star: 3.6 };
    const baseRot = it.r || 0;
    const common = { key: i, style: {
      position: 'absolute', left: `${it.x}%`, top: `${it.y}%`,
      transform: `translate(-50%, -50%)`,
      opacity: 0.96,
      animation: `${animMap[it.kind]} ${durMap[it.kind]}s ease-in-out ${(i % 9) * 0.23}s infinite`,
      transformOrigin: 'center',
      ['--base-rot']: `${baseRot}deg`,
      willChange: 'transform, opacity',
    }};
    switch (it.kind) {
      case 'robot':   return <div {...common}><Robot color="var(--ink)" size={it.s} rot={it.r}/></div>;
      case 'crab':    return <div {...common}><Crab color={p.accent} size={it.s} rot={it.r}/></div>;
      case 'block':   return <div {...common}><Block color="var(--ink)" fill={it.fill} size={it.s} rot={it.r} label={it.label}/></div>;
      case 'coin':    return <div {...common}><Coin color="var(--ink)" fill="oklch(0.82 0.14 85)" size={it.s}/></div>;
      case 'sparkle': return <div {...common}><Sparkle color="oklch(0.78 0.14 85)" size={it.s}/></div>;
      case 'star':    return <div {...common}><Star4 color="var(--ink)" size={it.s}/></div>;
      default: return null;
    }
  };

  return (
    <div aria-hidden="true" style={{
      position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none',
    }}>
      {all.map(render)}
    </div>
  );
};

const SignupForm = ({ tweaks }) => {
  const p = getPalette(tweaks);
  const [email, setEmail] = React.useState('');
  const [state, setState] = React.useState('idle'); // idle | sending | sent | error
  const [errorMsg, setErrorMsg] = React.useState('');

  const submit = async (e) => {
    e.preventDefault();
    if (!/^\S+@\S+\.\S+$/.test(email)) {
      setErrorMsg('Enter a valid email.');
      setState('error');
      return;
    }
    const cfg = (typeof window !== 'undefined' && window.__BEEHIIV__) || {};
    const endpoint = cfg.proxyUrl
      || (cfg.publicationId
          ? `https://api.beehiiv.com/v2/publications/${cfg.publicationId}/subscriptions`
          : null);
    if (!endpoint) {
      setErrorMsg('Signup is not configured yet.');
      setState('error');
      return;
    }
    setState('sending');
    setErrorMsg('');
    try {
      const headers = { 'Content-Type': 'application/json' };
      if (!cfg.proxyUrl && cfg.apiKey) headers['Authorization'] = `Bearer ${cfg.apiKey}`;
      const res = await fetch(endpoint, {
        method: 'POST',
        headers,
        body: JSON.stringify({
          email,
          reactivate_existing: true,
          send_welcome_email: true,
          utm_source: 'ai-garage-weekly-landing',
          referring_site: typeof window !== 'undefined' ? window.location.href : undefined,
        }),
      });
      if (!res.ok) {
        const text = await res.text().catch(() => '');
        throw new Error(text || `Request failed (${res.status}).`);
      }
      setState('sent');
    } catch (err) {
      setErrorMsg((err && err.message) || 'Something went wrong. Try again.');
      setState('error');
    }
  };

  const busy = state === 'sending' || state === 'sent';
  const label = state === 'sending' ? 'Sending…'
              : state === 'sent' ? '✓ Welcome in'
              : 'Subscribe →';

  return (
    <div style={{ maxWidth: 620, width: '100%' }}>
      <form onSubmit={submit} style={{
        display: 'flex', alignItems: 'stretch', gap: 0,
        background: 'var(--paper)',
        border: '2.5px solid var(--ink)',
        borderRadius: 6,
        boxShadow: '5px 5px 0 var(--ink)',
        width: '100%',
        transform: 'rotate(-0.4deg)',
        overflow: 'hidden',
      }}>
        <input
          type="email"
          value={email}
          onChange={(e) => { setEmail(e.target.value); if (state !== 'sending') { setState('idle'); setErrorMsg(''); } }}
          placeholder="you@yourcompany.com"
          disabled={busy}
          className="mono signup-input"
          style={{
            flex: 1, minWidth: 0, padding: '20px 22px',
            border: 'none', outline: 'none', background: 'transparent',
            fontSize: 17, color: 'var(--ink)',
          }}
        />
        <button type="submit" disabled={busy} className="mono signup-btn" style={{
          padding: '20px 28px',
          border: 'none', borderLeft: '2.5px solid var(--ink)',
          background: p.accent, color: 'var(--paper)',
          fontSize: 16, fontWeight: 700, letterSpacing: '0.12em',
          textTransform: 'uppercase', cursor: busy ? 'default' : 'pointer',
          opacity: state === 'sending' ? 0.8 : 1,
          flexShrink: 0, whiteSpace: 'nowrap',
        }}>
          {label}
        </button>
      </form>
      {state === 'error' && errorMsg && (
        <div className="mono" role="alert" style={{
          marginTop: 10, fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase',
          color: 'var(--red-ink)', transform: 'rotate(-0.3deg)',
        }}>
          ⚠ {errorMsg}
        </div>
      )}
    </div>
  );
};

const Hero = ({ tweaks }) => {
  const p = getPalette(tweaks);
  return (
    <section style={{
      position: 'relative',
      background: `linear-gradient(180deg, ${p.sky} 0%, ${p.sky} 70%, ${p.skyDeep} 100%)`,
      minHeight: '100vh',
      display: 'flex',
      flexDirection: 'column',
    }}>
      {/* top bar */}
      <div className="top-bar" style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '18px 28px',
        borderBottom: '2px solid var(--ink)',
        position: 'relative', zIndex: 2,
        background: 'var(--ink)',
        gap: 16,
      }}>
        <a href="https://youtube.com/@OnchainAIGarage" target="_blank" rel="noopener"
           className="mono top-bar-link" style={{
          fontSize: 15, fontWeight: 800, letterSpacing: '0.18em', textTransform: 'uppercase',
          color: 'var(--paper)', textDecoration: 'none',
          borderBottom: '2px solid var(--paper)',
          paddingBottom: 2,
        }}>
          ▶ From the creator of Onchain AI Garage
        </a>
        <div className="mono top-bar-stats" style={{
          fontSize: 15, fontWeight: 800, letterSpacing: '0.18em', textTransform: 'uppercase',
          color: 'var(--paper)',
        }}>
          ◆ 10K+ Subscribers · 300K+ Views
        </div>
      </div>

      {/* doodles behind content */}
      <DoodleField tweaks={tweaks} />

      {/* main stack */}
      <div style={{
        flex: 1,
        display: 'flex', flexDirection: 'column', justifyContent: 'center',
        alignItems: 'center',
        padding: '60px 24px',
        position: 'relative', zIndex: 1,
      }}>
        {/* tiny kicker */}
        <div className="mono" style={{
          display: 'inline-block',
          padding: '6px 14px',
          background: 'var(--paper)',
          border: '1.5px solid var(--ink)',
          borderRadius: 999,
          fontSize: 11, fontWeight: 600, letterSpacing: '0.22em',
          textTransform: 'uppercase',
          transform: 'rotate(-1.2deg)',
          marginBottom: 22,
          boxShadow: '2px 2px 0 var(--ink)',
        }}>
          A newsletter for AI tinkerers
        </div>

        <Wordmark tweaks={tweaks} />

        {/* tagline */}
        <p style={{
          maxWidth: 920,
          textAlign: 'center',
          fontSize: 'clamp(26px, 3.4vw, 44px)',
          lineHeight: 1.25,
          color: 'var(--paper)',
          margin: '38px auto 32px',
          fontStyle: 'italic',
          fontWeight: 700,
          background: 'var(--ink)',
          padding: '14px 26px',
          borderRadius: 6,
          border: '2px solid var(--ink)',
          boxShadow: '4px 4px 0 var(--ink)',
          transform: 'rotate(-0.4deg)',
          display: 'inline-block',
        }}>
          Latest AI news, interesting research finds, current ML experiments, and unique project ideas.
        </p>

        {/* signup */}
        <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14, width: '100%', maxWidth: 660 }}>
          <SignupForm tweaks={tweaks} />
          <div className="mono" style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--ink)' }}>
            Free · every Friday · 5 min read
          </div>
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { Hero, PALETTES, DISPLAY_FONTS, getPalette, getFont });
