/* myRico — coming soon
   System notes (out loud, like a junior designer briefing their PM):
   - Brand DNA: deep near-black, single electric blue accent (#2F6BFF-ish), glowing nodes/edges.
   - Type: a clean modern grotesk for UI ("Inter Tight"), and a mono ("JetBrains Mono") for
     metadata, status pills, and the timestamped "thinking" log — gives it a control-room feel,
     fitting for a "Chief of Staff" product. No third font.
   - Layout: full-bleed dark hero. Wordmark top-left, status pill top-right.
     Center column = oversized tagline + a one-line product description + waitlist form.
     Behind it: animated network constellation (canvas) — the logo's nodes coming alive.
     Bottom rail: a fake live "operator log" ticking through synthetic activity, plus founder note.
   - Constraint: zero filler. No feature grid, no FAQ, no "About us". This is a teaser.
*/

const { useState, useEffect, useRef, useMemo } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#2F6BFF",
  "headline": "An AI Quarterback for founders and leaders.",
  "logoMode": "wordmark",
  "constellationDensity": 22
}/*EDITMODE-END*/;

// ---------- Constellation backdrop ----------
function Constellation({ accent, density }) {
  const canvasRef = useRef(null);
  const rafRef = useRef(0);

  useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    let w = 0, h = 0, dpr = Math.min(window.devicePixelRatio || 1, 2);

    const resize = () => {
      const rect = canvas.getBoundingClientRect();
      w = rect.width; h = rect.height;
      canvas.width = w * dpr; canvas.height = h * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    resize();
    window.addEventListener('resize', resize);

    // Seed nodes — a primary "hub" plus orbital satellites, echoing the logo.
    const N = density;
    const nodes = Array.from({ length: N }, (_, i) => {
      const isHub = i < 3;
      return {
        x: Math.random() * w,
        y: Math.random() * h,
        vx: (Math.random() - 0.5) * 0.18,
        vy: (Math.random() - 0.5) * 0.18,
        r: isHub ? 5 + Math.random() * 4 : 1.4 + Math.random() * 1.6,
        hub: isHub,
        pulse: Math.random() * Math.PI * 2,
      };
    });

    // Parse accent to rgb
    const hex = accent.replace('#','');
    const R = parseInt(hex.slice(0,2),16), G = parseInt(hex.slice(2,4),16), B = parseInt(hex.slice(4,6),16);

    let t = 0;
    const tick = () => {
      t += 0.016;
      ctx.clearRect(0, 0, w, h);

      // Move
      for (const n of nodes) {
        n.x += n.vx; n.y += n.vy;
        if (n.x < -20) n.x = w + 20; if (n.x > w + 20) n.x = -20;
        if (n.y < -20) n.y = h + 20; if (n.y > h + 20) n.y = -20;
        n.pulse += 0.03;
      }

      // Edges — only between near-ish nodes
      const maxD = Math.min(w, h) * 0.22;
      for (let i = 0; i < nodes.length; i++) {
        for (let j = i + 1; j < nodes.length; j++) {
          const a = nodes[i], b = nodes[j];
          const dx = a.x - b.x, dy = a.y - b.y;
          const d = Math.hypot(dx, dy);
          if (d < maxD) {
            const alpha = (1 - d / maxD) * (a.hub || b.hub ? 0.55 : 0.18);
            ctx.strokeStyle = `rgba(${R},${G},${B},${alpha.toFixed(3)})`;
            ctx.lineWidth = a.hub || b.hub ? 1 : 0.6;
            ctx.beginPath();
            ctx.moveTo(a.x, a.y);
            ctx.lineTo(b.x, b.y);
            ctx.stroke();
          }
        }
      }

      // Nodes
      for (const n of nodes) {
        const pulse = n.hub ? 0.5 + 0.5 * Math.sin(n.pulse) : 1;
        // Glow
        if (n.hub) {
          const grad = ctx.createRadialGradient(n.x, n.y, 0, n.x, n.y, n.r * 8);
          grad.addColorStop(0, `rgba(${R},${G},${B},${0.45 * pulse})`);
          grad.addColorStop(1, `rgba(${R},${G},${B},0)`);
          ctx.fillStyle = grad;
          ctx.beginPath();
          ctx.arc(n.x, n.y, n.r * 8, 0, Math.PI * 2);
          ctx.fill();
        }
        ctx.fillStyle = `rgba(${R},${G},${B},${n.hub ? 0.95 : 0.7})`;
        ctx.beginPath();
        ctx.arc(n.x, n.y, n.r, 0, Math.PI * 2);
        ctx.fill();
      }

      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);

    return () => {
      cancelAnimationFrame(rafRef.current);
      window.removeEventListener('resize', resize);
    };
  }, [accent, density]);

  return <canvas ref={canvasRef} className="constellation" />;
}

// ---------- Synthetic operator log ----------
const LOG_TEMPLATES = [
  { tag: 'INBOX',    text: 'Triaged 47 emails — 3 flagged for founder review' },
  { tag: 'TASK',     text: 'Following up with Sarah (Acme) re: term sheet redlines' },
  { tag: 'CALENDAR', text: 'Rescheduled 2 conflicts; held Friday afternoon for deep work' },
  { tag: 'BRIEF',    text: 'Prepped 1-pager for 3pm board call' },
  { tag: 'NUDGE',    text: 'Pinged Marcus on the hiring loop — 4 days silent' },
  { tag: 'DIGEST',   text: 'Slack overnight: 12 threads summarized, 2 need you' },
  { tag: 'INBOX',    text: 'Drafted reply to investor intro from Pat — awaiting approval' },
  { tag: 'TASK',     text: 'Closed 6 follow-ups; opened 2 from this morning\'s standup' },
  { tag: 'BRIEF',    text: 'Compiled weekly metrics — revenue +12%, churn flat' },
  { tag: 'NUDGE',    text: 'Reminded Eng team: design review moved to Thursday' },
];

function OperatorLog({ accent }) {
  const [lines, setLines] = useState(() => LOG_TEMPLATES.slice(0, 4).map((l, i) => ({ ...l, id: i, t: timeAgo(i) })));
  const counter = useRef(4);

  useEffect(() => {
    const id = setInterval(() => {
      const next = LOG_TEMPLATES[counter.current % LOG_TEMPLATES.length];
      counter.current++;
      setLines(prev => [{ ...next, id: counter.current, t: 'just now' }, ...prev.slice(0, 3)]);
    }, 2800);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="log">
      <div className="log-head">
        <span className="log-dot" style={{ background: accent }} />
        <span className="log-title">OPERATOR · LIVE</span>
        <span className="log-meta">synthetic preview</span>
      </div>
      <div className="log-body">
        {lines.map((l, i) => (
          <div key={l.id} className="log-row" style={{ opacity: 1 - i * 0.22 }}>
            <span className="log-time">{l.t}</span>
            <span className="log-tag" style={{ color: accent, borderColor: `${accent}55` }}>{l.tag}</span>
            <span className="log-text">{l.text}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function timeAgo(i) {
  const mins = [2, 7, 14, 23][i] ?? 30;
  return `${mins}m ago`;
}

// ---------- Waitlist form ----------
function Waitlist({ accent }) {
  const [email, setEmail] = useState('');
  const [state, setState] = useState('idle'); // idle | submitting | done | error
  const [role, setRole] = useState('Founder');

  const submit = (e) => {
    e.preventDefault();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      setState('error');
      return;
    }
    setState('submitting');
    const subject = encodeURIComponent('Would love to learn more about myRico');
    const body = encodeURIComponent(
      `Please contact me with details.\n\n— ${email}${role ? ` (${role})` : ''}`
    );
    // Open the user's mail client with a prefilled message
    window.location.href = `mailto:hello@myrico.ai?subject=${subject}&body=${body}`;
    setTimeout(() => setState('done'), 600);
  };

  if (state === 'done') {
    return (
      <div className="waitlist-done">
        <div className="check" style={{ borderColor: accent, color: accent }}>✓</div>
        <div>
          <div className="done-title">Check your mail app.</div>
          <div className="done-sub">We just opened a draft to hello@myrico.ai — hit send and we'll be in touch.</div>
        </div>
      </div>
    );
  }

  return (
    <form className="waitlist" onSubmit={submit}>
      <div className="role-row">
        {['Founder', 'Chief of Staff', 'Operator', 'Investor'].map(r => (
          <button
            type="button"
            key={r}
            className={`role-chip ${role === r ? 'active' : ''}`}
            style={role === r ? { borderColor: accent, color: accent } : null}
            onClick={() => setRole(r)}
          >{r}</button>
        ))}
      </div>
      <div className="email-row">
        <input
          type="email"
          value={email}
          onChange={e => { setEmail(e.target.value); if (state === 'error') setState('idle'); }}
          placeholder="you@company.com"
          className={state === 'error' ? 'err' : ''}
          autoComplete="email"
        />
        <button
          type="submit"
          className="submit"
          style={{ background: accent }}
          disabled={state === 'submitting'}
        >
          {state === 'submitting' ? 'Joining…' : 'Request access'}
          <span className="arrow">→</span>
        </button>
      </div>
      <div className="form-meta">
        {state === 'error'
          ? <span style={{ color: '#ff6a6a' }}>Please enter a valid email.</span>
          : <span>Private beta · Q3 2026 · Invite-only</span>}
      </div>
    </form>
  );
}

// ---------- Main page ----------
function Page() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const accent = tweaks.accent;

  // Sync accent into a CSS variable so component-level styles can reference it
  useEffect(() => {
    document.documentElement.style.setProperty('--accent', accent);
  }, [accent]);

  return (
    <div className="page">
      <Constellation accent={accent} density={tweaks.constellationDensity} />
      <div className="vignette" />

      <header className="topbar">
        <div className="brand">
          {tweaks.logoMode === 'wordmark' ? (
            <img src="assets/myrico-wordmark.png" alt="myRico" className="wordmark" />
          ) : (
            <>
              <img src="assets/myrico-mark.png" alt="" className="mark" />
              <span className="brand-text">myRico</span>
            </>
          )}
        </div>
        <div className="status-pill">
          <span className="pulse" style={{ background: accent }} />
          <span>STEALTH · BUILDING</span>
        </div>
      </header>

      <main className="hero">
        <div className="eyebrow">
          <span className="line" />
          <span>COMING · 2026</span>
        </div>
        <h1 className="headline">
          {tweaks.headline.split(' ').map((w, i, arr) => (
            <span key={i} className={i >= arr.length - 3 ? 'h-accent' : ''}>
              {w}{i < arr.length - 1 ? ' ' : ''}
            </span>
          ))}
        </h1>
        <p className="lede">
          A secure, proactive operating layer for running your organization.
          <span className="lede-accent"> You make the calls. Rico runs the plays.</span>
        </p>

        <Waitlist accent={accent} />
      </main>

      <aside className="bottom-rail">
        <div className="formula">
          <span className="formula-token">memory</span>
          <span className="formula-op" style={{ color: accent }}>×</span>
          <span className="formula-token">capability</span>
          <span className="formula-op" style={{ color: accent }}>×</span>
          <span className="formula-token">security</span>
        </div>
      </aside>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Brand" />
        <TweakColor label="Accent" value={tweaks.accent}
          onChange={v => setTweak('accent', v)} />
        <TweakRadio label="Logo" value={tweaks.logoMode}
          options={['wordmark', 'mark']}
          onChange={v => setTweak('logoMode', v)} />

        <TweakSection label="Copy" />
        <TweakText label="Headline" value={tweaks.headline}
          onChange={v => setTweak('headline', v)} />

        <TweakSection label="Backdrop" />
        <TweakSlider label="Constellation" value={tweaks.constellationDensity}
          min={6} max={60} step={1} unit=" nodes"
          onChange={v => setTweak('constellationDensity', v)} />

      </TweaksPanel>

      <footer className="footer">
        <div className="footer-left">
          <span className="dot-sep">©</span> 2026 myRico, Inc.
          <span className="dot-sep">·</span> Built for founders
        </div>
        <div className="footer-right">
          <a href="mailto:hello@myrico.ai">hello@myrico.ai</a>
        </div>
      </footer>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<Page />);
