/* global React */
/* welcome.jsx — punk brain landing page.
   No rail (demo shows the rail inside the iframe). Click anywhere opens
   a login modal (Google / GitHub). */

const { useState, useEffect, useRef } = React;

/* ───── Demo cycle — prompts paired with view ids in Ask ───── */
const DEMOS = [
  { id: 'grant',    prompt: 'where are we at with the grant application?', tone: 'pk' },
  { id: 'calendar', prompt: 'what’s on my calendar this week?',            tone: 'gn' },
  { id: 'blockers', prompt: 'what’s blocked on me right now?',             tone: 'pk' },
  { id: 'sophia',   prompt: 'show me the sophia brand deals side by side', tone: 'gn' },
  { id: 'money',    prompt: 'how’s the money this quarter?',               tone: 'pk' },
  { id: 'uv',       prompt: 'what happened with uv in the last thirty days?', tone: 'gn' },
];

/* ───── The cycling ask-bar + preview frame ───── */
function DemoCycler({ iframeRef, iframeReady }) {
  const [idx, setIdx] = useState(0);
  const [phase, setPhase] = useState('typing');
  const [typed, setTyped] = useState('');

  const cur = DEMOS[idx];
  const next = () => setIdx(i => (i + 1) % DEMOS.length);

  useEffect(() => {
    if (phase !== 'typing') return;
    let i = 0;
    const full = cur.prompt;
    setTyped('');
    const t = setInterval(() => {
      i++;
      setTyped(full.slice(0, i));
      if (i >= full.length) { clearInterval(t); setPhase('holding'); }
    }, 32);
    return () => clearInterval(t);
  }, [phase, cur]);

  useEffect(() => {
    if (phase !== 'holding') return;
    const t = setTimeout(() => {
      if (iframeReady && iframeRef.current?.contentWindow) {
        iframeRef.current.contentWindow.postMessage(
          { type: '__run_view', id: cur.id }, '*'
        );
      }
      setPhase('viewing');
    }, 420);
    return () => clearTimeout(t);
  }, [phase, cur, iframeReady]);

  useEffect(() => {
    if (phase !== 'viewing') return;
    const t = setTimeout(() => setPhase('erasing'), 5200);
    return () => clearTimeout(t);
  }, [phase]);

  useEffect(() => {
    if (phase !== 'erasing') return;
    let i = typed.length;
    const t = setInterval(() => {
      i -= 2;
      if (i <= 0) {
        clearInterval(t);
        setTyped('');
        next();
        setPhase('typing');
      } else {
        setTyped(prev => prev.slice(0, i));
      }
    }, 16);
    return () => clearInterval(t);
  }, [phase]);

  const jump = (e, i) => {
    e.stopPropagation();
    setPhase('typing');
    setIdx(i);
  };

  return (
    <div className="wc-bar-wrap" onClick={(e) => e.stopPropagation()}>
      <div className={`wc-bar ${cur.tone}`}>
        <span className="wc-bar-kbd">⌘K</span>
        <span className="wc-bar-text">
          {typed}
          <span className="wc-bar-caret" aria-hidden="true"></span>
        </span>
        <span className="wc-bar-ret">↵</span>
      </div>

      <div className="wc-bar-track">
        {DEMOS.map((d, i) => (
          <button
            key={d.id}
            className={`wc-bar-dot ${d.tone}${i === idx ? ' on' : ''}`}
            aria-label={`jump to ${d.prompt}`}
            onClick={(e) => jump(e, i)}
          ></button>
        ))}
      </div>
    </div>
  );
}

/* ───── Login modal ───── */
function LoginModal({ onClose }) {
  const stop = (e) => e.stopPropagation();
  const enter = () => { window.location.href = 'Ask.html'; };

  // esc to close
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  return (
    <div className="wc-login-scrim" onClick={onClose}>
      <div className="wc-login" onClick={stop} role="dialog" aria-label="sign in">
        <div className="wc-login-kicker">sign in</div>
        <h2 className="wc-login-title">
          <em>welcome to</em><br />
          <em className="pk">punk brain</em>
        </h2>
        <p className="wc-login-note">
          small + private. invite-only right now — matty &amp; spencer.
        </p>

        <button className="wc-login-btn google" onClick={enter}>
          <svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true">
            <path fill="#4285F4" d="M17.64 9.2c0-.64-.06-1.25-.17-1.84H9v3.48h4.84a4.14 4.14 0 01-1.79 2.72v2.26h2.9c1.7-1.56 2.69-3.87 2.69-6.62z"/>
            <path fill="#34A853" d="M9 18c2.43 0 4.47-.8 5.96-2.18l-2.9-2.26c-.81.54-1.84.86-3.06.86-2.36 0-4.36-1.59-5.07-3.73H.92v2.33A9 9 0 009 18z"/>
            <path fill="#FBBC05" d="M3.93 10.7A5.4 5.4 0 013.64 9c0-.59.1-1.17.29-1.7V4.96H.92A9 9 0 000 9c0 1.45.35 2.82.96 4.04l2.97-2.33z"/>
            <path fill="#EA4335" d="M9 3.58c1.32 0 2.5.45 3.44 1.35l2.58-2.58C13.46.89 11.43 0 9 0A9 9 0 00.92 4.96L3.93 7.3C4.64 5.15 6.64 3.58 9 3.58z"/>
          </svg>
          <span>continue with google</span>
        </button>

        <button className="wc-login-btn github" onClick={enter}>
          <svg width="18" height="18" viewBox="0 0 16 16" aria-hidden="true">
            <path fill="currentColor" d="M8 0C3.58 0 0 3.58 0 8a8 8 0 005.47 7.59c.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82a7.42 7.42 0 014 0c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0016 8c0-4.42-3.58-8-8-8z"/>
          </svg>
          <span>continue with github</span>
        </button>

        <button className="wc-login-close" onClick={onClose} aria-label="close">
          esc
        </button>
      </div>
    </div>
  );
}

function WelcomeCanvas() {
  const iframeRef = useRef(null);
  const [iframeReady, setIframeReady] = useState(false);
  const [loginOpen, setLoginOpen] = useState(false);

  useEffect(() => {
    const onMsg = (e) => {
      if (e.source === iframeRef.current?.contentWindow &&
          e.data?.type === '__edit_mode_available') {
        setIframeReady(true);
      }
    };
    window.addEventListener('message', onMsg);
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const openLogin = () => setLoginOpen(true);
  const closeLogin = () => setLoginOpen(false);

  return (
    <main className="wc wc-full" onClick={openLogin}>
      <section className="wc-hero">
        <h1 className="wc-title">
          <em className="pk">punk brain:</em> frontier intelligence
          <br />
          for <em className="gn">artists</em> and <em className="gn">managers</em>.
        </h1>

        <DemoCycler iframeRef={iframeRef} iframeReady={iframeReady} />
      </section>

      <section className="wc-demo" onClick={(e) => e.stopPropagation()}>
        <div className="wc-demo-frame">
          <div className="wc-demo-chrome">
            <span className="tl r"></span><span className="tl y"></span><span className="tl g"></span>
            <span className="wc-demo-host">ask.punk-brain</span>
            <span className="wc-demo-live">live</span>
          </div>
          <div className="wc-demo-scale">
            <iframe
              ref={iframeRef}
              className="wc-demo-iframe"
              src="Ask.html?demo=1"
              title="punk brain · live demo"
              loading="lazy"
            />
          </div>
        </div>
        <div className="wc-demo-caption">
          <span className="wc-demo-hint">sit here a minute. it cycles.</span>
          <span className="wc-demo-hint wc-demo-cta">
            <em>click anywhere</em> to sign in →
          </span>
        </div>
      </section>

      <section className="wc-layers">
        <div className="wc-sec">the layers</div>
        <div className="wc-stack">
          <div className="wc-layer l0">
            <div className="wc-layer-k">L0 · personal</div>
            <div className="wc-layer-t"><em>matty’s brain</em> · <em>spencer’s brain</em></div>
            <div className="wc-layer-note">private. yours. never rendered down.</div>
          </div>
          <div className="wc-layer l1">
            <div className="wc-layer-k">L1 · substrate</div>
            <div className="wc-layer-t"><em>punk brain</em></div>
            <div className="wc-layer-note">shared positions, receipts, the bus.</div>
          </div>
          <div className="wc-layer l2">
            <div className="wc-layer-k">L2 · companies</div>
            <div className="wc-layer-t"><em>uv</em> · <em>different gear</em></div>
            <div className="wc-layer-note">each one inherits from punk brain.</div>
          </div>
          <div className="wc-layer l3">
            <div className="wc-layer-k">L3 · subjects</div>
            <div className="wc-layer-t"><em>sophia stel</em> · <em>warhol grant</em> · <em>brooklyn, night two</em></div>
            <div className="wc-layer-note">the actual things in flight. people, tours, contracts, money.</div>
          </div>
        </div>
      </section>

      <section className="wc-foot">
        <div className="wc-foot-note">
          last sync <em>just now</em> · audit live · shared with matty &amp; spencer · <em className="wc-foot-cta">click anywhere to sign in</em>
        </div>
      </section>

      {loginOpen && <LoginModal onClose={closeLogin} />}
    </main>
  );
}

function WelcomeApp() {
  useEffect(() => {
    const onMsg = (e) => {
      if (e.data?.type === '__activate_edit_mode') document.body.classList.add('tweaks-open');
      if (e.data?.type === '__deactivate_edit_mode') document.body.classList.remove('tweaks-open');
    };
    window.addEventListener('message', onMsg);
    window.parent?.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  return <WelcomeCanvas />;
}

ReactDOM.createRoot(document.getElementById('app')).render(<WelcomeApp />);
