/* RCC AI Holdings — v2: editorial-serif, story-driven, minimal copy */

/* ============ NAV ============ */
const Nav2 = () => (
  <nav className="nav nav2">
    <Logo />
    <div className="nav-links">
      <a href="#what">What</a>
      <a href="#why">Why</a>
      <a href="#how">How</a>
      <a href="#book">Book</a>
    </div>
    <a href="#book" className="btn btn-sm">
      Book a meeting
      <svg className="arr" width="14" height="14" viewBox="0 0 24 24" fill="none">
        <path d="M5 12h14M13 6l6 6-6 6" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    </a>
  </nav>
);

/* ============ HERO — kinetic story walkthrough ============ */
const STORY = [
  { eyebrow: '§ 01 · TODAY', text: ['Your HR team is', 'drowning in', 'repeat work.'], emph: 2 },
  { eyebrow: '§ 02 · THE GAP', text: ['Vendors sell', 'demos.', 'You need leverage.'], emph: 2 },
  { eyebrow: '§ 03 · WHAT CHANGED', text: ['Agents now', 'learn from', 'every loop.'], emph: 1 },
  { eyebrow: '§ 04 · THE OPPORTUNITY', text: ['One operator', 'can do the work', 'of a team of twenty.'], emph: 2 },
  { eyebrow: '§ 05 · WHO WE ARE', text: ['We build the', 'agents.', 'We train your people.'], emph: 1 },
];

const HeroStory = ({ rotateMs = 4200 }) => {
  const [i, setI] = React.useState(0);
  const [paused, setPaused] = React.useState(false);

  React.useEffect(() => {
    if (paused) return;
    const t = setInterval(() => setI((x) => (x + 1) % STORY.length), rotateMs);
    return () => clearInterval(t);
  }, [paused, rotateMs]);

  const cur = STORY[i];

  return (
    <section className="hero-story" id="hero" onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}>
      <div className="hs-eyebrow mono">{cur.eyebrow}</div>
      <div className="hs-stage">
        <div className="hs-text" key={i}>
          {cur.text.map((line, li) => (
            <div key={li} className={`hs-line ${li === cur.emph ? 'hs-emph' : ''}`} style={{ animationDelay: `${li * 140}ms` }}>
              {line}
            </div>
          ))}
        </div>
      </div>
      <div className="hs-controls">
        <div className="hs-dots">
          {STORY.map((_, di) => (
            <button key={di} className={`hs-dot ${di === i ? 'is-active' : ''}`} onClick={() => setI(di)} aria-label={`Story ${di + 1}`} />
          ))}
        </div>
        <a href="#book" className="btn">
          Book a 30-min meeting
          <svg className="arr" width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M5 12h14M13 6l6 6-6 6" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </a>
      </div>
      <div className="hs-foot mono">
        <span>RCC.AI · 26.04</span>
        <span className="hs-foot-r">{paused ? 'PAUSED' : `AUTO · ${(rotateMs / 1000).toFixed(1)}s`}</span>
      </div>
    </section>
  );
};

/* ============ WHAT — three crisp tiles ============ */
const What = () => (
  <section className="what" id="what">
    <div className="what-head">
      <div className="eyebrow"><span className="dot" />§ WHAT</div>
      <h2 className="serif-display">
        We build the <span className="hl-coral">AI</span> your<br/>
        people function <span className="serif-italic">needs.</span>
      </h2>
    </div>
    <div className="what-grid">
      <article className="what-card">
        <div className="what-num serif-italic">01</div>
        <div className="what-tag mono">STRATEGY</div>
        <h3 className="serif-display what-title">A <span className="serif-italic">roadmap</span> you can ship.</h3>
        <p className="what-body">Two weeks. We diagnose your stack, rank the leverage, and hand you a buildable 30/60/90.</p>
      </article>
      <article className="what-card">
        <div className="what-num serif-italic">02</div>
        <div className="what-tag mono">PRODUCTS</div>
        <h3 className="serif-display what-title">A working <span className="serif-italic">agent.</span></h3>
        <p className="what-body">Thirty days. We write the code, frontend and backend, on your data. You keep it.</p>
      </article>
      <article className="what-card">
        <div className="what-num serif-italic">03</div>
        <div className="what-tag mono">UPSKILLING</div>
        <h3 className="serif-display what-title">A team that <span className="serif-italic">uses</span> it.</h3>
        <p className="what-body">Workshops for HRBPs, recruiters, and managers. Real workflows. Adoption is the deliverable.</p>
      </article>
    </div>
  </section>
);

/* ============ WHY — data-led ============ */
const Why = ({ loopSpeed = 1800, loopAccent = '#E8553A', showBars = true }) => (
  <section className="why" id="why">
    <div className="why-head">
      <div className="eyebrow"><span className="dot" />§ WHY NOW</div>
      <h2 className="serif-display">
        Agents now <span className="serif-italic">learn</span><br/>
        from every <span className="hl-coral serif-italic">loop.</span>
      </h2>
      <p className="why-sub">The math has changed. Static automation is over. The new generation closes a loop (act, observe, adjust) and gets measurably better the more it runs.</p>
    </div>

    <SelfImprovingLoop speed={loopSpeed} accent={loopAccent} showBars={showBars} />

    <div className="why-stats">
      <StatCard value="80" suffix="%" label="time saved on individual tasks" cite="Anthropic, 2025 · sample of 100k Claude conversations" />
      <StatCard value="94" suffix="%" label="of HR inquiries answered without a human" cite="IBM AskHR, 2025" />
      <StatCard value="75" suffix="%" label="faster on manager workflows like promotions" cite="IBM, 2025" />
      <StatCard value="4.5" prefix="$" suffix="B" label="productivity unlocked at one company" cite="IBM AI &amp; automation, 2023–2025" />
      <StatCard value="36" suffix="%" label="gain for the bottom-skill quintile" cite="Brynjolfsson, Li &amp; Raymond · 5,172-agent study" />
      <StatCard value="92" suffix="%" label="of companies are increasing AI spend" cite="McKinsey, 2025" />
    </div>

    <div className="why-quote">
      <div className="why-quote-mark serif-italic">"</div>
      <blockquote className="serif-display">
        The leaders are pulling away. The companies pulling ahead are <span className="serif-italic">two times more likely</span> to use AI in autonomous, self-optimising ways.
      </blockquote>
      <cite className="mono why-cite">PwC AI Performance Study · April 2026</cite>
    </div>
  </section>
);

const StatCard = ({ value, suffix = '', prefix = '', label, cite }) => {
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(0);
  React.useEffect(() => {
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        const target = parseFloat(value);
        const start = performance.now();
        const dur = 1400;
        const tick = (t) => {
          const p = Math.min(1, (t - start) / dur);
          const eased = 1 - Math.pow(1 - p, 3);
          setShown(target * eased);
          if (p < 1) requestAnimationFrame(tick);
        };
        requestAnimationFrame(tick);
        obs.disconnect();
      }
    }, { threshold: 0.4 });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, [value]);
  const decimals = String(value).includes('.') ? 1 : 0;
  return (
    <div className="stat-card" ref={ref}>
      <div className="stat-card-v mono">
        {prefix}{decimals > 0 ? shown.toFixed(decimals) : Math.round(shown)}{suffix}
      </div>
      <div className="stat-card-l">{label}</div>
      <div className="stat-card-c mono">{cite}</div>
    </div>
  );
};

/* Self-improving loop infographic */
const SelfImprovingLoop = ({ speed = 1800, accent = '#E8553A', showBars = true }) => {
  const [step, setStep] = React.useState(0);
  React.useEffect(() => {
    const t = setInterval(() => setStep((s) => (s + 1) % 4), speed);
    return () => clearInterval(t);
  }, [speed]);

  const stages = [
    { label: 'ACT',     sub: 'agent runs the task',  detail: 'plan · tool-call · execute' },
    { label: 'OBSERVE', sub: 'outcome is scored',    detail: 'eval · trace · diagnose' },
    { label: 'LEARN',   sub: 'lesson is stored',     detail: 'memory · pattern · prompt' },
    { label: 'ADJUST',  sub: 'next run is better',   detail: 'route · refine · promote' },
  ];

  // Layout: 4 stations on a circle, generous padding so nothing clips
  const cx = 480, cy = 320;
  const R = 200;
  const positions = stages.map((_, i) => {
    const a = -Math.PI / 2 + i * (Math.PI / 2);
    return { x: cx + R * Math.cos(a), y: cy + R * Math.sin(a), a };
  });

  const ink = '#0E0E0C';
  const cream = '#EFE9DD';

  return (
    <div className="loop">
      <div className="loop-head">
        <span className="loop-head-tag mono">§ FIG. 01 — CLOSED-LOOP AGENT</span>
      </div>

      <svg viewBox={`0 0 960 ${showBars ? 760 : 660}`} width="100%" style={{ display: 'block', maxWidth: 1040, margin: '0 auto' }} preserveAspectRatio="xMidYMid meet">
        <defs>
          <marker id="loop-arr-dark" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto">
            <path d="M 0 0 L 10 5 L 0 10 z" fill={ink} opacity="0.55" />
          </marker>
          <marker id="loop-arr-coral" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto">
            <path d="M 0 0 L 10 5 L 0 10 z" fill={accent} />
          </marker>
          <radialGradient id="loop-glow" cx="0.5" cy="0.5" r="0.5">
            <stop offset="0%"  stopColor={accent} stopOpacity="0.25" />
            <stop offset="60%" stopColor={accent} stopOpacity="0.05" />
            <stop offset="100%" stopColor={accent} stopOpacity="0" />
          </radialGradient>
        </defs>

        {/* corner marks */}
        <text x="40" y="36" fontFamily="'JetBrains Mono', monospace" fontSize="11" fill={ink} opacity="0.45" letterSpacing="3">FIG. 01 · CLOSED-LOOP AGENT</text>
        <text x="920" y="36" textAnchor="end" fontFamily="'JetBrains Mono', monospace" fontSize="11" fill={accent} opacity="0.7" letterSpacing="3">RCC · AI</text>

        {/* center glow */}
        <circle cx={cx} cy={cy} r="170" fill="url(#loop-glow)" />

        {/* central ring */}
        <circle cx={cx} cy={cy} r={R} fill="none" stroke={ink} strokeWidth="1" strokeDasharray="2 6" opacity="0.35" />

        {/* connecting arcs between stations (clockwise) */}
        {positions.map((p, i) => {
          const next = positions[(i + 1) % 4];
          const active = step === i;
          // sweep along the circle
          const start = p, end = next;
          // shorten endpoints so arrows don't pierce the circles
          const sa = -Math.PI / 2 + i * (Math.PI / 2);
          const ea = -Math.PI / 2 + (i + 1) * (Math.PI / 2);
          const inset = 64; // node radius + buffer
          const Rs = R;
          const sx = cx + Rs * Math.cos(sa + 0.18);
          const sy = cy + Rs * Math.sin(sa + 0.18);
          const ex = cx + Rs * Math.cos(ea - 0.18);
          const ey = cy + Rs * Math.sin(ea - 0.18);
          // large-arc=0, sweep=1 (clockwise)
          return (
            <path
              key={`arc-${i}`}
              d={`M ${sx} ${sy} A ${Rs} ${Rs} 0 0 1 ${ex} ${ey}`}
              fill="none"
              stroke={active ? accent : ink}
              strokeWidth={active ? 2 : 1.2}
              opacity={active ? 1 : 0.45}
              markerEnd={active ? 'url(#loop-arr-coral)' : 'url(#loop-arr-dark)'}
              style={{ transition: 'stroke 380ms, opacity 380ms, stroke-width 380ms' }}
            />
          );
        })}

        {/* center label */}
        <g transform={`translate(${cx} ${cy})`}>
          <text textAnchor="middle" y="-8" fontFamily="'Instrument Serif', Georgia, serif" fontStyle="italic" fontSize="34" fill={ink}>self-improving</text>
          <text textAnchor="middle" y="26" fontFamily="'JetBrains Mono', monospace" fontSize="11" fill={ink} opacity="0.55" letterSpacing="3">CYCLE {String(step + 1).padStart(2, '0')} / 04</text>
          <line x1="-60" y1="44" x2="60" y2="44" stroke={ink} opacity="0.25" />
          <text textAnchor="middle" y="64" fontFamily="'JetBrains Mono', monospace" fontSize="10" fill={accent} letterSpacing="2">{stages[step].label}</text>
        </g>

        {/* 4 stations */}
        {stages.map((s, i) => {
          const p = positions[i];
          const active = step === i;

          // Position outer caption based on which cardinal point this is
          // i=0: top   → caption above the node
          // i=1: right → caption to the right
          // i=2: bottom → caption below
          // i=3: left  → caption to the left
          let lx, ly, anchor;
          if (i === 0)      { lx = p.x;       ly = p.y - 92; anchor = 'middle'; }
          else if (i === 1) { lx = p.x + 78;  ly = p.y;      anchor = 'start'; }
          else if (i === 2) { lx = p.x;       ly = p.y + 100; anchor = 'middle'; }
          else              { lx = p.x - 78;  ly = p.y;      anchor = 'end'; }

          return (
            <g key={`st-${i}`}>
              {/* outer halo when active */}
              {active && (
                <circle cx={p.x} cy={p.y} r="72" fill="none" stroke={accent} strokeWidth="1" opacity="0.35">
                  <animate attributeName="r" from="58" to="84" dur="1.4s" repeatCount="indefinite" />
                  <animate attributeName="opacity" from="0.5" to="0" dur="1.4s" repeatCount="indefinite" />
                </circle>
              )}
              {/* node */}
              <circle cx={p.x} cy={p.y} r="58"
                fill={active ? accent : cream}
                stroke={ink}
                strokeWidth="1.4"
                style={{ transition: 'fill 380ms cubic-bezier(.2,.7,.2,1)' }} />
              {/* roman index */}
              <text x={p.x} y={p.y - 16} textAnchor="middle" fontFamily="'Instrument Serif', Georgia, serif" fontStyle="italic" fontSize="15"
                fill={active ? cream : ink} opacity={active ? 0.85 : 0.55}
                style={{ transition: 'fill 380ms, opacity 380ms' }}>
                {['i', 'ii', 'iii', 'iv'][i]}
              </text>
              {/* label */}
              <text x={p.x} y={p.y + 6} textAnchor="middle" fontFamily="'JetBrains Mono', monospace" fontSize="14" fontWeight="600"
                fill={active ? cream : ink} letterSpacing="2.5"
                style={{ transition: 'fill 380ms' }}>{s.label}</text>
              {/* sub */}
              <text x={p.x} y={p.y + 28} textAnchor="middle" fontFamily="'Instrument Serif', Georgia, serif" fontStyle="italic" fontSize="13"
                fill={active ? cream : ink} opacity={active ? 0.92 : 0.6}
                style={{ transition: 'fill 380ms, opacity 380ms' }}>{s.sub}</text>

              {/* outer detail caption — only show when active so it doesn't compete */}
              <text x={lx} y={ly} textAnchor={anchor} fontFamily="'JetBrains Mono', monospace" fontSize="10" fill={accent} opacity={active ? 1 : 0} letterSpacing="2.5"
                style={{ transition: 'opacity 380ms' }}>{s.detail.toUpperCase()}</text>
            </g>
          );
        })}

        {/* compounding bars — well below the circle */}
        {showBars && (
        <g transform="translate(60, 680)">
          <text x="0" y="0" fontFamily="'JetBrains Mono', monospace" fontSize="10" fill={ink} opacity="0.55" letterSpacing="2.5">PERFORMANCE OVER CYCLES</text>
          <line x1="0" y1="14" x2="840" y2="14" stroke={ink} opacity="0.18" />
          {Array.from({ length: 14 }).map((_, n) => {
            const h = 12 + n * 4.2;
            const isPast = n <= (step + 1) * 3;
            return (
              <rect
                key={n}
                x={n * 60}
                y={60 - h}
                width="34"
                height={h}
                fill={isPast ? accent : ink}
                opacity={isPast ? 0.92 : 0.18}
                style={{ transition: 'fill 380ms, opacity 380ms' }}
              />
            );
          })}
          <text x="840" y="104" textAnchor="end" fontFamily="'Instrument Serif', Georgia, serif" fontStyle="italic" fontSize="16" fill={accent}>compounds →</text>
        </g>
        )}
      </svg>

      <div className="loop-cap serif-italic">Each cycle teaches the next. An agent built today becomes <span className="hl-coral">measurably more useful</span> next quarter.</div>
    </div>
  );
};

/* ============ HOW — 3 steps ============ */
const How = () => (
  <section className="how" id="how">
    <div className="how-head">
      <div className="eyebrow"><span className="dot" />§ HOW</div>
      <h2 className="serif-display">
        Three meetings.<br/>
        Then we <span className="hl-coral serif-italic">build.</span>
      </h2>
    </div>
    <div className="how-grid">
      <article className="how-step">
        <div className="how-step-num serif-italic">i.</div>
        <h3 className="serif-display how-step-title">Diagnose</h3>
        <p className="how-step-body">One call. Where's the leverage in your people stack? We tell you in 30 minutes.</p>
        <div className="how-step-meta mono">~30 min · free</div>
      </article>
      <article className="how-step">
        <div className="how-step-num serif-italic">ii.</div>
        <h3 className="serif-display how-step-title">Design</h3>
        <p className="how-step-body">A scoped, fixed-fee plan. What we'll build, in what order, paid against outcomes.</p>
        <div className="how-step-meta mono">1 week · 1-page proposal</div>
      </article>
      <article className="how-step">
        <div className="how-step-num serif-italic">iii.</div>
        <h3 className="serif-display how-step-title">Deploy</h3>
        <p className="how-step-body">We build the agent on your data, train your team to run it, and stay until it sticks.</p>
        <div className="how-step-meta mono">30–90 days · in production</div>
      </article>
    </div>
  </section>
);

/* ============ ABOUT (compact) ============ */
const About2 = () => (
  <section className="about2">
    <div className="about2-eyebrow eyebrow"><span className="dot" />§ WHO</div>
    <p className="about2-text serif-display">
      We <span className="serif-italic">build</span> it. We <span className="serif-italic">implement</span> it. You enjoy the <span className="hl-coral serif-italic">business outcomes.</span>
    </p>
  </section>
);

/* ============ BOOK A MEETING ============ */
const Book = () => {
  const [form, setForm] = React.useState({ name: '', email: '', company: '', whats_broken: '', website: '' });
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState(null);
  const upd = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  const submit = async (e) => {
    e.preventDefault();
    setSending(true);
    setError(null);
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || 'Something went wrong. Please try again.');
      setSent(true);
    } catch (err) {
      setError(err.message);
    } finally {
      setSending(false);
    }
  };
  return (
    <section className="book" id="book">
      <div className="book-grid">
        <div className="book-left">
          <div className="eyebrow"><span className="dot" />§ BOOK</div>
          <h2 className="serif-display">
            Tell us what's <span className="serif-italic">broken.</span><br/>
            We'll tell you what's <span className="hl-coral serif-italic">buildable.</span>
          </h2>
          <p className="book-sub">30-minute call. No deck, no pitch. Just a real conversation about your people stack and where AI fits.</p>
          <ul className="book-meta">
            <li><span className="mono">REPLY</span><span>within 48 hours</span></li>
            <li><span className="mono">CALL</span><span>30 min · free</span></li>
            <li><span className="mono">EMAIL</span><span>hello@rccai.ai</span></li>
          </ul>
        </div>
        <form className="book-form" onSubmit={submit}>
          {sent ? (
            <div className="book-sent">
              <svg width="44" height="44" viewBox="0 0 24 24" fill="none"><path d="M5 13l4 4L19 7" stroke="#E8553A" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
              <h3 className="serif-display">Got it.</h3>
              <p>We'll reply with a calendar link inside 48 hours.</p>
            </div>
          ) : (
            <>
              <label><span className="mono">NAME</span><input type="text" required value={form.name} onChange={upd('name')} placeholder="Jane Doe" /></label>
              <label><span className="mono">EMAIL</span><input type="email" required value={form.email} onChange={upd('email')} placeholder="jane@company.com" /></label>
              <label><span className="mono">COMPANY</span><input type="text" value={form.company} onChange={upd('company')} placeholder="Where you work" /></label>
              <label><span className="mono">WHAT'S BROKEN</span><textarea rows="3" value={form.whats_broken} onChange={upd('whats_broken')} placeholder="One sentence is plenty." /></label>
              <input
                type="text"
                name="website"
                tabIndex="-1"
                autoComplete="off"
                value={form.website}
                onChange={upd('website')}
                style={{ position: 'absolute', left: '-9999px', width: '1px', height: '1px', opacity: 0 }}
                aria-hidden="true"
              />
              {error && <div className="book-error" role="alert">{error}</div>}
              <button className="btn book-submit" type="submit" disabled={sending}>
                {sending ? 'Sending…' : 'Book the meeting'}
                <svg className="arr" width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M5 12h14M13 6l6 6-6 6" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/></svg>
              </button>
            </>
          )}
        </form>
      </div>
    </section>
  );
};

/* ============ FOOTER ============ */
const Footer2 = ({ showCTA = true }) => (
  <footer className="footer2">
    <div className="footer2-logo-wrap">
      <img src="assets/rcc-logo-cream.png" alt="RCC AI" className="logo-img footer-logo" />
    </div>
    {showCTA && (
      <div className="footer2-cta">
        <a href="#book" className="btn">
          Book a 30-min meeting
          <svg className="arr" width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M5 12h14M13 6l6 6-6 6" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </a>
      </div>
    )}
    <div className="footer2-bottom">
      <span className="mono">© 2026 RCC AI</span>
      <span className="mono">BUILT, NOT PITCHED · v3.0</span>
    </div>
  </footer>
);

Object.assign(window, { Nav2, HeroStory, What, Why, How, About2, Book, Footer2, SelfImprovingLoop });
