// components.jsx — Section components for the relatIQ landing page

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

/* ─────────────────────────── Brand / Nav ─────────────────────────── */

function BrandMark({ name = "relatIQ" }) {
  return (
    <div className="brand">
      <img src="assets/logo.png" alt="relatIQ Logo" className="brand-logo" style={{ width: 24, height: 24, borderRadius: 6 }} />
      <div className="brand-name">{name}<em>.</em></div>
    </div>
  );
}

function Nav({ name }) {
  return (
    <nav className="nav">
      <BrandMark name={name} />
      <div className="nav-links">
        <a href="#how">How it works</a>
        <a href="#use-cases">For founders</a>
        <a href="#founder">Why we're building it</a>
        <a href="#waitlist" className="btn btn-ghost btn-sm">Request invite</a>
      </div>
    </nav>
  );
}

/* ─────────────────────────── Hero with rotating product visuals ─────────────────────────── */

const GOALS = [
  "raising a seed round",
  "hiring a founding engineer",
  "lining up design partners",
  "warming up dormant investors",
  "finding a co-founder",
  "closing a Series A",
];

function GoalRotator() {
  const [i, setI] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setI(x => (x + 1) % GOALS.length), 2400);
    return () => clearInterval(t);
  }, []);
  return (
    <span style={{ display: "inline-block", position: "relative", color: "var(--accent)", fontStyle: "italic" }}>
      <span key={i} style={{ display: "inline-block", animation: "fadeUp 480ms cubic-bezier(.22,.61,.36,1)" }}>
        {GOALS[i]}
      </span>
    </span>
  );
}

function ChatCard() {
  return (
    <>
      <div className="cc-head">
        <div className="cc-dots"><i></i><i></i><i></i></div>
        <div className="cc-title">Draft · Maya Chen, GP at Foundry</div>
        <div style={{ width: 22 }}></div>
      </div>
      <div className="cc-body">
        <div className="chat-msg">
          <div className="av">YOU</div>
          <div className="chat-bubble">
            Help me follow up with Maya. She said reconnect after Q3 once we had real revenue.
            <div style={{ marginTop: 6 }}>
              <span className="ctx">+ goal: seed round</span>{" "}
              <span className="ctx">+ 4 past msgs</span>
            </div>
          </div>
        </div>
        <div className="chat-msg ai">
          <div className="av ai">R</div>
          <div className="chat-bubble">
            She's been at Foundry 7 yrs, leads B2B SaaS at seed. Last note: <em>"loved the wedge, come back at $30k MRR."</em> You hit $42k in March — lead with that.
            <div className="chat-draft">
              <div className="label">Draft · matched to <span style={{color:"var(--accent)"}}>goal: seed round</span></div>
              Hey Maya — closing the loop from June. We hit $42k MRR last month, mostly inbound from the workflow you flagged as the real wedge. Worth a 20 min call this week? Tues/Thurs both work.<span className="caret"></span>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

function ProfileCard() {
  return (
    <>
      <div className="cc-head">
        <div className="cc-dots"><i></i><i></i><i></i></div>
        <div className="cc-title">Profile · Daniel Osei</div>
        <div style={{ width: 22 }}></div>
      </div>
      <div className="cc-body">
        <div className="prof-head">
          <div className="prof-avatar">DO</div>
          <div>
            <div className="prof-name">Daniel Osei</div>
            <div className="prof-title">Staff Eng → Eng Lead candidate · Stripe, then Ramp</div>
          </div>
        </div>
        <div className="prof-tags">
          <span className="tag warm">2nd-degree</span>
          <span className="tag">payments infra</span>
          <span className="tag">ex-founder (2019)</span>
          <span className="tag">writes a Substack</span>
        </div>
        <div className="insight">
          <span className="lbl">Why he matches your goal</span>
          He shipped the API rewrite at Ramp — exactly the surface you're hiring for. Left in March.
        </div>
        <div className="next-step">
          <div className="next-step-title">Recommended next step</div>
          <div className="next-step-action">
            <span className="num">1</span>
            <span>Ask Priya for an intro — she worked with him at Stripe and replied to your last DM in 3 hrs.</span>
          </div>
          <div className="next-step-action">
            <span className="num">2</span>
            <span>Reference his March essay on idempotency — it overlaps your infra roadmap.</span>
          </div>
        </div>
      </div>
    </>
  );
}

function CRMCard() {
  const rows = [
    { name: "Maya Chen",    init: "MC", meta: "Foundry · GP",        goal: "seed round",        status: "active" },
    { name: "Priya Shah",   init: "PS", meta: "Stripe · Eng Mgr",    goal: "founding eng hire", status: "warm"   },
    { name: "Daniel Osei",  init: "DO", meta: "Eng Lead candidate",  goal: "founding eng hire", status: "intro"  },
    { name: "Tomás Rivera", init: "TR", meta: "Sequoia · Principal", goal: "seed round",        status: "warm"   },
    { name: "Lin Park",     init: "LP", meta: "Design partner #3",   goal: "design partners",   status: "active" },
    { name: "Jordan Vey",   init: "JV", meta: "First Round · Scout", goal: "seed round",        status: "cold"   },
  ];
  return (
    <>
      <div className="cc-head">
        <div className="cc-dots"><i></i><i></i><i></i></div>
        <div className="cc-title">Pipeline · auto-triaged across 3 goals</div>
        <div style={{ width: 22 }}></div>
      </div>
      <div className="cc-body">
        <div className="crm-row crm-head-row">
          <span>Person</span>
          <span>Goal</span>
          <span>Status</span>
        </div>
        {rows.map(r => (
          <div className="crm-row" key={r.name}>
            <div className="crm-name">
              <span className="crm-dot">{r.init}</span>
              <span>
                <div>{r.name}</div>
                <div className="crm-meta">{r.meta}</div>
              </span>
            </div>
            <span className="crm-meta" style={{fontFamily:"var(--mono)", color:"var(--accent)", fontSize:11}}>
              ⊹ {r.goal}
            </span>
            <span className={`status ${r.status}`}>
              {r.status === "intro" ? "Intro" : r.status === "active" ? "Active" : r.status === "warm" ? "Warm" : "Cold"}
            </span>
          </div>
        ))}
      </div>
    </>
  );
}

function HeroStage() {
  const [active, setActive] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setActive(a => (a + 1) % 3), 5200);
    return () => clearInterval(t);
  }, []);
  const cards = [
    { key: "chat",    label: "Draft", node: <ChatCard /> },
    { key: "profile", label: "Analyze", node: <ProfileCard /> },
    { key: "crm",     label: "Pipeline", node: <CRMCard /> },
  ];
  // pos 0 = front, 1 = mid, 2 = back. relative offset from active.
  const posOf = (i) => (i - active + 3) % 3;

  return (
    <div className="stage" data-screen-label="Hero stage">
      {cards.map((c, i) => (
        <div className="stage-card" key={c.key} data-pos={posOf(i)}>
          {c.node}
        </div>
      ))}
      <div className="stage-tabs">
        {cards.map((c, i) => (
          <button
            key={c.key}
            className={"stage-tab" + (i === active ? " active" : "")}
            onClick={() => setActive(i)}
          >{c.label}</button>
        ))}
      </div>
    </div>
  );
}

function Hero({ name }) {
  return (
    <header className="shell hero" data-screen-label="01 Hero">
      <div className="hero-aura" aria-hidden="true"></div>
      <div className="hero-copy">
        <span className="badge-invite">
          <span className="badge-dot"></span>
          Invite-only beta
          <span className="mono">/ founders first</span>
        </span>
        <h1>
          The relationship copilot that <span className="alt">already&nbsp;knows</span> who you're talking to.
        </h1>
        <p className="lede">
          {name} is a private workspace for anyone serious about LinkedIn
          outreach. Run multiple goals in parallel — <GoalRotator /> — and we
          auto-triage every relationship into the goal it actually serves. Your
          context, the profile, every past message: held for you, on tap.
        </p>
        <div className="hero-cta">
          <a href="#waitlist" className="btn btn-primary">Join the beta waitlist <span aria-hidden="true">→</span></a>
          <a href="#how" className="btn btn-ghost">See how it works</a>
        </div>
        <div className="hero-meta">
          <span>Free during beta</span>
          <span className="sep"></span>
          <span>LinkedIn first — email + calendar next</span>
          <span className="sep"></span>
          <span>Hand-reviewed invites</span>
        </div>
      </div>
      <HeroStage />
    </header>
  );
}

/* ─────────────────────────── Differentiator ─────────────────────────── */

function Differentiator() {
  return (
    <section className="section" id="how">
      <div className="shell diff-grid">
        <div className="section-head">
          <span className="eyebrow"><span className="num">01 ―</span> Why it's different</span>
          <h2 className="diff-headline">Context is the work. We do that part.</h2>
          <p className="lede">
            Generic AI gives generic advice because you can't reasonably paste five
            profiles, a goal doc, and three months of DMs into a chat box every
            time. We hold that context for you, per relationship, automatically.
          </p>
        </div>
        <div className="diff-comparison">
          <div className="compare-card bad">
            <div className="compare-lbl">The usual flow</div>
            <pre className="compare-snippet">{`> open LinkedIn
> copy profile
> paste into ChatGPT
> "here's my goal..."
> "here's our last 4 messages..."
> "and the round we're raising is..."
> get generic draft
> rewrite it anyway
> repeat tomorrow`}</pre>
          </div>
          <div className="compare-card good">
            <div className="compare-lbl">With relatIQ</div>
            <pre className="compare-snippet">{`> "draft a follow-up to Maya"

✓ goal: seed round
✓ profile: indexed
✓ past 4 msgs: attached
✓ tone: matches yours
✓ next step: suggested

  send.`}</pre>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────── Triage (multi-goal) ─────────────────────────── */

function Triage() {
  const cols = [
    {
      lbl: "goal_01", title: "Close $2M seed by Q3", meta: "14 relationships",
      rows: [
        { who: "Maya Chen",    role: "Foundry · GP",         tag: "warm" },
        { who: "Tomás Rivera", role: "Sequoia · Principal",  tag: "intro" },
        { who: "Jordan Vey",   role: "First Round · Scout",  tag: "reconnect" },
      ],
    },
    {
      lbl: "goal_02", title: "Hire founding engineer", meta: "9 relationships",
      rows: [
        { who: "Daniel Osei",  role: "Staff Eng · ex-Ramp",  tag: "reach out" },
        { who: "Priya Shah",   role: "Stripe · Eng Mgr",     tag: "intro path" },
        { who: "Sana Iyer",    role: "Infra · ex-Linear",    tag: "replied" },
      ],
    },
    {
      lbl: "goal_03", title: "5 design partner calls", meta: "7 relationships",
      rows: [
        { who: "Lin Park",     role: "VP Ops · Notion",       tag: "onboarding" },
        { who: "Marc Allard",  role: "COO · mid-market SaaS", tag: "send update" },
        { who: "Hana Kim",     role: "Head of Growth",        tag: "first reply" },
      ],
    },
  ];
  return (
    <section className="section" id="triage">
      <div className="shell">
        <div className="section-head">
          <span className="eyebrow"><span className="num">02 ―</span> Multiple goals, auto-triaged</span>
          <h2>Run several goals at once. We sort the people for you.</h2>
          <p className="lede">
            Add a goal in plain English. Every relationship you bring in — new connections,
            second-degree intros, dormant ties — is routed to the goal it actually serves.
            Re-tag any time. One person can sit across more than one.
          </p>
        </div>
        <div className="triage">
          <div className="triage-head">
            {cols.map(c => (
              <div className="triage-col-h" key={c.lbl}>
                <span className="gh-lbl">{c.lbl}</span>
                <span className="gh-title">{c.title}</span>
                <span className="gh-meta">→ {c.meta}</span>
              </div>
            ))}
          </div>
          <div className="triage-body">
            {cols.map((c, ci) => (
              <div className="triage-col" key={c.lbl}>
                {c.rows.map((r, ri) => (
                  <div className="triage-card" key={r.who}
                    style={{ animationDelay: `${(ci*3 + ri) * 90}ms` }}>
                    <span className="av-sm">{r.who.split(" ").map(s => s[0]).slice(0,2).join("")}</span>
                    <span style={{ display: "flex", flexDirection: "column", gap: 1, minWidth: 0 }}>
                      <span className="who">{r.who}</span>
                      <span className="role">{r.role}</span>
                    </span>
                    <span className="auto-tag">{r.tag}</span>
                  </div>
                ))}
              </div>
            ))}
          </div>
          <div className="triage-foot">
            <span className="live-dot"></span>
            auto-triage running · last sync 2 min ago · 30 relationships across 3 goals
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────── Use cases ─────────────────────────── */

const USE_CASES = [
  {
    n: "01",
    title: "Closing a round.",
    body: "Track every investor conversation in one place. Get a nudge when it's time to send the update Maya asked for, with the right metric called out.",
    goal: "→ founder · close $2M seed by Q3",
  },
  {
    n: "02",
    title: "Hiring the first ten.",
    body: "Surface 2nd-degree engineers who shipped the exact thing you need. Draft outreach in your voice with a real reason to reach out.",
    goal: "→ founder · founding engineer, infra",
  },
  {
    n: "03",
    title: "Finding design partners.",
    body: "Identify operators who've felt the pain you solve. Open with their words, not yours — and remember what they said.",
    goal: "→ founder · 5 design partner calls",
  },
  {
    n: "04",
    title: "Warming up dormant ties.",
    body: "Old colleagues, second-degree friends, the investor who passed politely. Re-open with context they'll actually recognize.",
    goal: "→ founder · 10 reactivated relationships",
  },
];

function UseCases() {
  const slides = [
    ...USE_CASES,
    {
      n: "05",
      title: "…and many more.",
      body: "Recruiters sourcing passive candidates. Sales leads working a 50-account list. Job-seekers re-warming dormant ties. PMs lining up customer-dev calls. Same workflow, your goal.",
      goal: "→ you · tell us yours",
      isMore: true,
    },
  ];
  const [i, setI] = useState(0);
  const total = slides.length;
  const go = (d) => setI(x => (x + d + total) % total);

  const wrapRef = useRef(null);
  const [slideW, setSlideW] = useState(0);
  useEffect(() => {
    if (!wrapRef.current) return;
    const measure = () => setSlideW(wrapRef.current.clientWidth);
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(wrapRef.current);
    return () => ro.disconnect();
  }, []);
  const GAP = 16;

  return (
    <section className="section" id="use-cases">
      <div className="shell">
        <div className="slider-head">
          <div className="section-head">
            <span className="eyebrow"><span className="num">03 ―</span> What people are doing with it</span>
            <h2>Same workflow. Different goals.</h2>
            <p className="lede">
              We're starting with founders because that's where our network is. The product is
              built for anyone serious about LinkedIn outreach — swipe through.
            </p>
          </div>
          <div className="slider-ctrl">
            <span className="slider-counter">
              <span className="sc-i">{String(i + 1).padStart(2, "0")}</span>
              <span className="sc-sep">/</span>
              <span className="sc-t">{String(total).padStart(2, "0")}</span>
            </span>
            <div className="slider-btns">
              <button className="slider-btn" onClick={() => go(-1)} aria-label="Previous">←</button>
              <button className="slider-btn" onClick={() => go(1)} aria-label="Next">→</button>
            </div>
          </div>
        </div>
        <div className="slider-track-wrap" ref={wrapRef}>
          <div className="slider-track" style={{ transform: `translateX(${-i * (slideW + GAP)}px)` }}>
            {slides.map(u => (
              <article className={"usecase slide" + (u.isMore ? " slide-more" : "")} key={u.n}>
                <span className="usecase-num">{u.n}</span>
                <h3>{u.title}</h3>
                <p>{u.body}</p>
                {u.isMore ? (
                  <a href="#waitlist" className="more-cta">apply with your goal →</a>
                ) : (
                  <div className="usecase-goal">
                    <span className="arrow">{u.goal.split(" ")[0]}</span>
                    <span>{u.goal.replace(/^→\s*/, "")}</span>
                  </div>
                )}
              </article>
            ))}
          </div>
        </div>
        <div className="slider-dots">
          {slides.map((_, idx) => (
            <button key={idx} className={"slider-dot" + (idx === i ? " on" : "")}
              onClick={() => setI(idx)} aria-label={`Slide ${idx+1}`} />
          ))}
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────── Founder note ─────────────────────────── */

function FounderNote({ name }) {
  return (
    <section className="section" id="founder">
      <div className="shell founder">
        <aside className="founder-card">
          <div className="founder-portrait">[ portrait — Abhishek ]</div>
          <div className="founder-meta">
            <span className="who">Abhishek · founder, {name}</span>
            <span className="role">building from a kitchen table in Bangalore</span>
          </div>
        </aside>
        <div className="founder-body">
          <span className="eyebrow"><span className="num">04 ―</span> Why we're building this</span>
          <div className="founder-quote">
            "I wrote the same three paragraphs of context into ChatGPT a hundred times last
            quarter. The drafts were fine. <em>I was the bottleneck.</em>"
          </div>
          <p>
            Everyone serious about LinkedIn outreach runs a small private CRM in their head —
            who they met, what they promised, the one investor still owed an update. The tools
            we have don't help much. LinkedIn is a content firehose. CRMs are for sales teams.
            ChatGPT is brilliant but starts from zero every time.
          </p>
          <p>
            {name} is the opposite. You add a goal, you add the people — and from then on every
            draft, analysis and nudge is grounded in the full picture: your goal, the profile,
            every past message. Multiple goals run in parallel and we triage relationships into
            the right one automatically.
          </p>
          <p>
            We're invite-only because we're small, and the feedback from the first batch decides
            what this becomes. Founders go first because that's where my network is — but the
            waitlist is open to anyone with a real outreach goal. Tell us what you're working on.
          </p>
          <div className="signature">— Abhishek</div>
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────── Waitlist ─────────────────────────── */

const GOAL_CHIPS = [
  "Raising a round",
  "Hiring (eng)",
  "Hiring (non-eng)",
  "Sales / BD outreach",
  "Recruiting candidates",
  "Design partners",
  "Customer dev",
  "Job search",
  "Reactivating dormant ties",
  "Warm intros to investors",
  "Something else",
];

function Waitlist({ name }) {
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [link, setLink] = useState("");
  const [goals, setGoals] = useState(["Raising a round", "Hiring (eng)"]);
  const [note, setNote] = useState("");
  const [done, setDone] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

  const toggle = (g) => setGoals(gs => gs.includes(g) ? gs.filter(x => x !== g) : [...gs, g]);

  const API_BASE = "https://api.relatiq.co";

  const submit = async (e) => {
    e.preventDefault();
    if (!email || !link || submitting) return;
    setSubmitting(true);
    setError("");
    try {
      const res = await fetch(`${API_BASE}/invite-requests`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, phone, linkedin_url: link, goals, note }),
      });
      if (!res.ok) throw new Error("Failed to submit");
      setDone(true);
    } catch {
      setError("Something went wrong — please try again or email us directly.");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section className="section" id="waitlist">
      <div className="shell">
        <div className="waitlist">
          {done ? (
            <div className="wait-success">
              <div className="ok-mark">✓</div>
              <h2>You're on the list.</h2>
              <p className="lede" style={{ textAlign: "center" }}>
                We'll review every application by hand. If your goals fit, you'll hear from us
                with an invite link within a week. Keep an eye on <span className="u-mono">{email || "your inbox"}</span>.
              </p>
              <button className="btn btn-ghost" onClick={() => { setDone(false); setEmail(""); setLink(""); setNote(""); }}>← Back to form</button>
            </div>
          ) : (
            <div className="wait-grid">
              <div className="wait-side">
                <span className="eyebrow"><span className="num">05 ―</span> Apply for an invite</span>
                <h3>Tell us what you're building. We'll get back to you.</h3>
                <div className="wait-bullets">
                  <div className="wait-bullet">
                    <span className="bn">01</span>
                    <span>
                      <b>Free during beta.</b>
                      Soft caps on drafts and analyses while we scale. No credit card.
                    </span>
                  </div>
                  <div className="wait-bullet">
                    <span className="bn">02</span>
                    <span>
                      <b>Hand-reviewed.</b>
                      We read every application. The goal you share helps us prioritize.
                    </span>
                  </div>
                  <div className="wait-bullet">
                    <span className="bn">03</span>
                    <span>
                      <b>Founders first, then everyone.</b>
                      Starting with founders for network reasons · widening to BD, recruiters, job-seekers and beyond as we grow.
                    </span>
                  </div>
                  <div className="wait-bullet">
                    <span className="bn">04</span>
                    <span>
                      <b>You shape it.</b>
                      Beta users get a direct line and meaningfully change the roadmap.
                    </span>
                  </div>
                </div>
                <div className="wait-fineprint">
                  Your data is yours. We process profiles and conversations only with your consent and never train shared models on them.
                </div>
              </div>
              <form className="wait-form" onSubmit={submit}>
                <div className="field">
                  <label>Email <span style={{color:"var(--accent)"}}>required</span></label>
                  <input type="email" required placeholder="you@company.com"
                    value={email} onChange={e => setEmail(e.target.value)} />
                </div>
                <div className="field">
                  <label>Phone number</label>
                  <input type="tel" placeholder="+1 (555) 000-0000"
                    value={phone} onChange={e => setPhone(e.target.value)} />
                </div>
                <div className="field">
                  <label>LinkedIn profile <span style={{color:"var(--accent)"}}>required</span></label>
                  <input type="url" required placeholder="https://linkedin.com/in/..."
                    pattern="https?://([a-z]{2,3}\.)?linkedin\.com/.*"
                    title="Please paste your full LinkedIn profile URL."
                    value={link} onChange={e => setLink(e.target.value)} />
                </div>
                <div className="field">
                  <label>What are you working on right now? Pick any.</label>
                  <div className="chips">
                    {GOAL_CHIPS.map(g => (
                      <button type="button" key={g}
                        className={"chip" + (goals.includes(g) ? " on" : "")}
                        onClick={() => toggle(g)}>
                        {goals.includes(g) ? "✓ " : ""}{g}
                      </button>
                    ))}
                  </div>
                </div>
                <div className="field">
                  <label>One sentence on the specific goal</label>
                  <textarea placeholder="e.g. Close $2M seed by Q3 — 6 firms in the funnel, need to re-warm 3."
                    value={note} onChange={e => setNote(e.target.value)} />
                </div>
                {error && <p style={{ color: "var(--accent)", fontSize: 13, marginTop: 4 }}>{error}</p>}
                <div style={{ display: "flex", gap: 12, alignItems: "center", marginTop: 4 }}>
                  <button type="submit" className="btn btn-primary" disabled={submitting}>
                    {submitting ? "Submitting…" : "Request invite →"}
                  </button>
                  <span className="wait-fineprint">Avg reply: 3–5 days.</span>
                </div>
              </form>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────── Footer ─────────────────────────── */

function Footer({ name }) {
  return (
    <footer className="footer">
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <BrandMark name={name} />
        <span className="u-muted">© 2026 · made for founders, in private beta.</span>
      </div>
      <div className="footer-links">
        <a href="#waitlist">Request invite</a>
        <a href="#">Privacy</a>
        <a href="#">Contact</a>
      </div>
    </footer>
  );
}

/* expose */
Object.assign(window, {
  Nav, Hero, Differentiator, Triage, UseCases, FounderNote, Waitlist, Footer,
});
