// sections-top.jsx — Nav, Hero, Problem

// ─── Logo ────────────────────────────────────────────────────────────
function Wordmark({ small }) {
  return (
    <div style={{display:'inline-flex', alignItems:'center', gap: small ? 8 : 10}}>
      <IconLogo size={small ? 20 : 24} />
      <span style={{
        fontFamily: 'var(--serif)',
        fontWeight: 500,
        fontSize: small ? 17 : 19,
        letterSpacing: '-0.012em',
        color: 'var(--ink)'
      }}>
        Auto<span style={{color: 'var(--accent-2)'}}>·</span>Council
      </span>
    </div>
  );
}

// ─── Nav ─────────────────────────────────────────────────────────────
function Nav() {
  const [scrolled, setScrolled] = React.useState(false);
  const [open, setOpen] = React.useState(false);

  React.useEffect(() => {
    const on = () => setScrolled(window.scrollY > 12);
    on(); window.addEventListener('scroll', on, { passive: true });
    return () => window.removeEventListener('scroll', on);
  }, []);

  // Close mobile menu if viewport grows past the breakpoint
  React.useEffect(() => {
    const onResize = () => { if (window.innerWidth > 860 && open) setOpen(false); };
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, [open]);

  // Lock body scroll while the menu is open
  React.useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = open ? 'hidden' : prev;
    return () => { document.body.style.overflow = prev; };
  }, [open]);

  const go = (id) => (e) => {
    e.preventDefault();
    setOpen(false);
    // Allow the menu's pointer-events to clear before scrolling
    requestAnimationFrame(() => {
      const el = document.getElementById(id);
      if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    });
  };

  const links = [
    { id: 'product',    label: 'Product' },
    { id: 'how',        label: 'How it works' },
    { id: 'compliance', label: 'Compliance' },
    { id: 'pricing',    label: 'Pricing' },
    { id: 'faq',        label: 'FAQ' },
  ];

  return (
    <>
      <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
        <div className="wrap nav-inner">
          <a href="#top" onClick={go('top')} style={{textDecoration:'none'}}>
            <Wordmark small={scrolled} />
          </a>
          <div className="nav-links">
            {links.map(l => (
              <a key={l.id} className="nav-link" href={`#${l.id}`} onClick={go(l.id)}>{l.label}</a>
            ))}
            <a className="btn btn-primary" href="https://calendly.com/jakeciantar766/legal-ai-demo" target="_blank" rel="noreferrer" style={{fontSize:14, padding:'9px 14px'}}>
              Book a demo
            </a>
          </div>
          <button
            type="button"
            className="nav-toggle"
            aria-label={open ? 'Close menu' : 'Open menu'}
            aria-expanded={open}
            data-open={open ? 'true' : 'false'}
            onClick={() => setOpen(v => !v)}
          >
            <span className="bars"><span /></span>
          </button>
        </div>
      </nav>

      <div className="nav-mobile" data-open={open ? 'true' : 'false'} aria-hidden={!open}>
        {links.map(l => (
          <a key={l.id} className="nm-link" href={`#${l.id}`} onClick={go(l.id)}>{l.label}</a>
        ))}
        <a
          className="btn btn-primary nm-cta"
          href="https://calendly.com/jakeciantar766/legal-ai-demo"
          target="_blank"
          rel="noreferrer"
          onClick={() => setOpen(false)}
        >
          Book a demo
        </a>
      </div>
    </>
  );
}

// ─── Hero ────────────────────────────────────────────────────────────
const HEADLINES = {
  excel:   { h: 'Stop processing invoices in', accent: 'Excel.', tail: '' },
  skeda:   { h: 'The', accent: 'Skeda tal-Ħlasijiet,', tail: 'generated for you.' },
  finance: { h: 'Council finance,', accent: 'without the spreadsheets.', tail: '' },
};

function Hero({ headlineKey = 'finance' }) {
  const headline = HEADLINES[headlineKey] || HEADLINES.finance;

  return (
    <section id="top" style={{paddingTop: 32, paddingBottom: 96, borderTop: 0, position:'relative', overflow:'hidden'}}>
      {/* Atmospheric background */}
      <div className="hero-bg">
        <div className="grid" />
        <div className="blob3" />
      </div>

      <div className="wrap" style={{position:'relative', zIndex: 1}}>
        {/* Floating decorative pills on desktop only */}
        <FloatingPills />

        <div style={{display:'flex', flexDirection:'column', alignItems:'center', textAlign:'center', gap: 24, marginBottom: 64, maxWidth: 980, marginInline:'auto'}}>
          {/* Trust pill */}
          <div className="pill rise in" style={{marginTop: 8}}>
            <span className="pill-ico" aria-hidden="true">
              <span style={{
                display:'inline-block', width: 10, height: 10, borderRadius: 2,
                background: 'linear-gradient(135deg, var(--red) 0%, var(--red) 50%, #FFFFFF 50%, #FFFFFF 100%)',
              }} />
            </span>
            <span>Built for Maltese local councils</span>
            <span style={{width:1, height: 14, background:'var(--hairline)'}} />
            <span style={{color:'var(--ink-3)', display:'inline-flex', alignItems:'center', gap:5}}>
              <span style={{width:6, height:6, borderRadius:'50%', background:'var(--green)', boxShadow:'0 0 0 3px var(--green-tint)'}}/>
              In pilot rollout
            </span>
          </div>

          <h1 className="display h1 rise in" style={{margin: 0, textWrap: 'balance', maxWidth: '22ch'}}>
            {headline.h}{' '}
            <em>{headline.accent}</em>
            {headline.tail && <> {headline.tail}</>}
          </h1>

          <p className="lede rise in" style={{margin: 0, maxWidth: '58ch', textWrap:'pretty'}}>
            Auto-Council digitises your full invoice and procurement workflow and generates the
            DLG Schedule of Payments automatically. Councils processing around 100 invoices a month can save 1,000+ hours a year.
          </p>

          <div className="row gap-12 rise in" style={{marginTop: 8, flexWrap:'wrap', justifyContent:'center'}}>
            <a className="btn btn-primary" href="https://calendly.com/jakeciantar766/legal-ai-demo" target="_blank" rel="noreferrer">Book a 20-minute demo <IconArrowRight size={16} /></a>
            <a className="btn btn-ghost" href="#how">See how it works</a>
          </div>

          <div className="row gap-24 mt-16 rise in" style={{fontSize: 13, color:'var(--ink-3)', flexWrap:'wrap', justifyContent:'center'}}>
            <span style={{display:'inline-flex', alignItems:'center', gap:6}}><IconShield size={14} color="var(--accent-2)" /> EU data residency · Frankfurt</span>
            <span style={{width:3, height:3, borderRadius:'50%', background:'var(--ink-5)'}}/>
            <span style={{display:'inline-flex', alignItems:'center', gap:6}}><IconCheck size={14} color="var(--accent-2)" /> DLG-compliant Skeda format</span>
            <span style={{width:3, height:3, borderRadius:'50%', background:'var(--ink-5)'}}/>
            <span style={{display:'inline-flex', alignItems:'center', gap:6}}><IconBuilding size={14} color="var(--accent-2)" /> Maltese-built · Maltese-supported</span>
          </div>
        </div>

        <div className="rise in" style={{position:'relative'}}>
          <HeroViz />
        </div>
      </div>
    </section>
  );
}

// Floating decorative UI pills around the hero — invoice cards, stat bubbles
function FloatingPills() {
  // Position: absolute relative to the wrap, only visible on wider screens
  return (
    <div aria-hidden="true" className="float-pills" style={{position:'absolute', inset: 0, pointerEvents:'none', zIndex: 0}}>
      <style>{`
        .float-pills > * { position: absolute; box-shadow: var(--shadow-md); background: #fff; border: 1px solid var(--hairline); border-radius: 14px; padding: 10px 12px; font-size: 11.5px; }
        .float-pills .fp-1 { left: -8px; top: 40px; transform: rotate(-6deg); animation: floaty 6s ease-in-out infinite; }
        .float-pills .fp-2 { right: -4px; top: 24px; transform: rotate(5deg);  animation: floaty 7s ease-in-out infinite 1s; }
        .float-pills .fp-3 { left: 28px; top: 240px; transform: rotate(-4deg); animation: floaty 8s ease-in-out infinite 0.5s; }
        .float-pills .fp-4 { right: 8px; top: 280px; transform: rotate(4deg);  animation: floaty 9s ease-in-out infinite 1.5s; }
        @keyframes floaty {
          0%, 100% { transform: translateY(0) rotate(var(--r, -6deg)); }
          50%      { transform: translateY(-8px) rotate(var(--r, -6deg)); }
        }
        @media (max-width: 1100px) { .float-pills { display: none !important; } }
      `}</style>
      <div className="fp-1" style={{'--r':'-6deg'}}>
        <div style={{display:'flex', alignItems:'center', gap:8}}>
          <span style={{width:24, height:24, borderRadius:6, background:'var(--accent-tint)', color:'var(--accent-2)', display:'inline-flex', alignItems:'center', justifyContent:'center'}}>
            <IconFileText size={13} />
          </span>
          <div>
            <div style={{fontWeight:600, color:'var(--ink)', fontSize:11.5}}>New upload</div>
            <div style={{color:'var(--ink-4)', fontSize:10.5}}>Vella Electrical · €3,265.50</div>
          </div>
        </div>
      </div>
      <div className="fp-2" style={{'--r':'5deg'}}>
        <div style={{display:'flex', alignItems:'center', gap:8}}>
          <span style={{width:24, height:24, borderRadius:'50%', background:'var(--green-tint)', color:'var(--green)', display:'inline-flex', alignItems:'center', justifyContent:'center'}}>
            <IconCheck size={13} stroke={2.5} />
          </span>
          <div>
            <div style={{fontWeight:600, color:'var(--ink)', fontSize:11.5}}>Approved</div>
            <div style={{color:'var(--ink-4)', fontSize:10.5}}>D. Vassallo · 11:02</div>
          </div>
        </div>
      </div>
      <div className="fp-3" style={{'--r':'-4deg'}}>
        <div style={{display:'flex', alignItems:'center', gap:8}}>
          <span style={{width:24, height:24, borderRadius:6, background:'var(--accent-tint)', color:'var(--accent-2)', display:'inline-flex', alignItems:'center', justifyContent:'center'}}>
            <IconSparkle size={13} />
          </span>
          <div>
            <div style={{fontWeight:600, color:'var(--ink)', fontSize:11.5}}>AI extracted</div>
            <div style={{color:'var(--ink-4)', fontSize:10.5}}>Net €1,840 · VAT €331.20</div>
          </div>
        </div>
      </div>
      <div className="fp-4" style={{'--r':'4deg'}}>
        <div style={{display:'flex', alignItems:'center', gap:8}}>
          <span style={{width:24, height:24, borderRadius:6, background:'#0E1A33', color:'#fff', display:'inline-flex', alignItems:'center', justifyContent:'center'}}>
            <IconClipboard size={13} />
          </span>
          <div>
            <div style={{fontWeight:600, color:'var(--ink)', fontSize:11.5}}>Skeda exported</div>
            <div style={{color:'var(--ink-4)', fontSize:10.5}}>32 lines · €48,221</div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Problem section ─────────────────────────────────────────────────
function ProblemSection() {
  // Mock Excel data (chaotic) vs Auto-Council (clean)
  const messy = [
    { sup: 'stamperija borg', amt: '1840',  vat: '?',     code: '',    note: 'check w/ Daniel' },
    { sup: 'Vella Elec',       amt: '3265.5', vat: '587.79', code: 'T',  note: '' },
    { sup: 'skyclean',         amt: '620.00', vat: '111.6', code: '',   note: 'recurring?' },
    { sup: 'MALTAPOST',        amt: '148.20', vat: '26.68', code: 'DA', note: '' },
    { sup: 'Calleja Hardwre',  amt: '2410.75',vat: '433.94',code: 'D',  note: '' },
    { sup: 'TransMarine',      amt: '5890',   vat: '?',     code: '',   note: 'tender ref??' },
  ];

  // Refs for cells the annotations should point at
  const wrapRef = React.useRef(null);
  const cellRefs = {
    capRow1:    React.useRef(null), // "stamperija borg" — lowercase
    capRow4:    React.useRef(null), // "MALTAPOST" — all caps
    vatRow6:    React.useRef(null), // row 6 VAT "?"
    codeRow3:   React.useRef(null), // row 3 M·Code empty
    noteRow1:   React.useRef(null), // row 1 notes "check w/ Daniel"
  };

  const [pos, setPos] = React.useState(null);

  React.useLayoutEffect(() => {
    const compute = () => {
      const w = wrapRef.current;
      if (!w) return;
      const wr = w.getBoundingClientRect();
      const out = {};
      for (const [k, ref] of Object.entries(cellRefs)) {
        const c = ref.current;
        if (!c) continue;
        const cr = c.getBoundingClientRect();
        out[k] = {
          top:    cr.top - wr.top,
          left:   cr.left - wr.left,
          right:  cr.right - wr.left,
          bottom: cr.bottom - wr.top,
          cx:     cr.left - wr.left + cr.width / 2,
          cy:     cr.top - wr.top + cr.height / 2,
        };
      }
      out._wrap = { width: wr.width, height: wr.height };
      setPos(out);
    };
    compute();
    const t1 = setTimeout(compute, 250);  // fonts settle
    const t2 = setTimeout(compute, 800);
    const ro = new ResizeObserver(compute);
    if (wrapRef.current) ro.observe(wrapRef.current);
    window.addEventListener('resize', compute);
    return () => {
      clearTimeout(t1); clearTimeout(t2);
      ro.disconnect();
      window.removeEventListener('resize', compute);
    };
  }, []);

  // Annotation positions (anchored to wrapRef) — computed once pos is known.
  // Each annotation: { text, ax/ay (annot anchor point), tx/ty (target point), align }
  const annots = pos ? [
    {
      text: 'Inconsistent capitalisation',
      // Place above row 1 supplier, pointing down at it
      ax: pos.capRow1?.cx,
      ay: Math.max(8, (pos.capRow1?.top ?? 0) - 36),
      tx: pos.capRow1?.cx,
      ty: pos.capRow1?.top + 2,
      align: 'center',
    },
    {
      text: 'Missing VAT',
      // Place to the right of row 6 VAT cell
      ax: (pos.vatRow6?.right ?? 0) + 60,
      ay: pos.vatRow6?.cy,
      tx: pos.vatRow6?.right - 4,
      ty: pos.vatRow6?.cy,
      align: 'right',
    },
    {
      text: 'No codes assigned',
      // Place to the left of row 3 M·Code cell
      ax: (pos.codeRow3?.left ?? 0) - 60,
      ay: pos.codeRow3?.cy,
      tx: pos.codeRow3?.left + 4,
      ty: pos.codeRow3?.cy,
      align: 'left',
    },
    {
      text: 'Re-keyed every month',
      // Place below row 1 notes cell, pointing up at it
      ax: pos.noteRow1?.cx,
      ay: (pos.noteRow1?.bottom ?? 0) + 32,
      tx: pos.noteRow1?.cx,
      ty: pos.noteRow1?.bottom - 2,
      align: 'center',
    },
  ].filter(a => a.ax != null) : [];

  return (
    <section id="product">
      <div className="wrap">
        <div style={{maxWidth: 720, marginBottom: 56}}>
          <div className="eyebrow">The problem</div>
          <h2 className="display h2 mt-12" style={{margin:0, textWrap:'balance'}}>
            Same data. <span style={{color:'var(--ink-3)'}}>One eighth of the time.</span>
          </h2>
          <p className="lede mt-16" style={{margin:0}}>
            Most councils still cut and paste invoice data into Excel every month, then hand-key
            method and procurement codes, then rebuild the Skeda from scratch. It is fragile,
            it is slow, and it leaves no audit trail.
          </p>
        </div>

        <div style={{
          display: 'grid', gap: 28,
          gridTemplateColumns: 'repeat(auto-fit, minmax(360px, 1fr))',
          alignItems: 'start'
        }}>
          {/* Left: Excel chaos — needs extra horizontal/vertical room for annotations */}
          <div style={{position:'relative', padding: '52px 72px 56px 72px', margin: '-52px -72px -56px -72px', overflow:'hidden'}}>
            <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom: 14}}>
              <div style={{display:'flex', alignItems:'center', gap:8}}>
                <span style={{
                  width:18, height:18, borderRadius:3, background:'#217346',
                  display:'inline-flex', alignItems:'center', justifyContent:'center',
                  color:'#fff', fontSize:10, fontWeight:700, fontFamily:'var(--sans)'
                }}>X</span>
                <span style={{fontSize:13, color:'var(--ink-3)'}}>Skeda_April_2026_v7_FINAL_FINAL.xlsx</span>
              </div>
              <span className="tag" style={{background:'#FBE4E4', color:'var(--red)'}}>Manual</span>
            </div>

            <div ref={wrapRef} className="xl" style={{position:'relative'}}>
              <div className="xl-bar">
                <span>Skeda_April_2026_v7_FINAL_FINAL.xlsx · Last saved: 2 days ago</span>
                <span style={{opacity:0.85}}>Excel</span>
              </div>
              <table className="xl-grid">
                <thead>
                  <tr>
                    <th style={{width:24}}></th>
                    <th>Supplier</th>
                    <th>Amount</th>
                    <th>VAT</th>
                    <th>M·Code</th>
                    <th>Notes</th>
                  </tr>
                </thead>
                <tbody>
                  {messy.map((r, i) => (
                    <tr key={i}>
                      <td className="idx">{i+1}</td>
                      <td
                        ref={i === 0 ? cellRefs.capRow1 : (i === 3 ? cellRefs.capRow4 : null)}
                        className={r.sup.match(/[A-Z]{4,}/) || r.sup === r.sup.toLowerCase() ? 'warn' : ''}
                      >{r.sup}</td>
                      <td className={r.vat === '?' ? 'bad' : ''}>{r.amt}</td>
                      <td
                        ref={i === 5 ? cellRefs.vatRow6 : null}
                        className={r.vat === '?' ? 'bad' : ''}
                      >{r.vat}</td>
                      <td
                        ref={i === 2 ? cellRefs.codeRow3 : null}
                        className={!r.code ? 'bad' : ''}
                      >{r.code || '—'}</td>
                      <td
                        ref={i === 0 ? cellRefs.noteRow1 : null}
                        className={r.note ? 'warn' : ''}
                      >{r.note}</td>
                    </tr>
                  ))}
                </tbody>
              </table>

              {/* SVG leader-line overlay — fills the .xl bounds */}
              {pos && (
                <svg
                  aria-hidden="true"
                  style={{
                    position:'absolute', inset: 0, width: '100%', height: '100%',
                    pointerEvents:'none', overflow:'visible', zIndex: 1
                  }}
                >
                  {annots.map((a, i) => (
                    <g key={i}>
                      {/* dashed leader line */}
                      <line
                        x1={a.ax} y1={a.ay}
                        x2={a.tx} y2={a.ty}
                        stroke="var(--red)"
                        strokeWidth="1"
                        strokeDasharray="3 3"
                        opacity="0.75"
                      />
                      {/* small filled dot at target */}
                      <circle cx={a.tx} cy={a.ty} r="2.5" fill="var(--red)" />
                    </g>
                  ))}
                </svg>
              )}

              {/* Annotation labels — absolutely positioned to the .xl wrapper */}
              {annots.map((a, i) => {
                const transform = a.align === 'center' ? 'translate(-50%, -50%)'
                                 : a.align === 'right'  ? 'translate(0, -50%)'
                                 : 'translate(-100%, -50%)';
                return (
                  <div key={i} className="annot-pin" style={{
                    position:'absolute',
                    left: a.ax, top: a.ay,
                    transform,
                    zIndex: 2,
                    pointerEvents:'none'
                  }}>
                    {a.text}
                  </div>
                );
              })}
            </div>

            {/* Bottom summary stat — left as a clean caption, not an annotation */}
            <div style={{
              display:'flex', alignItems:'center', justifyContent:'space-between',
              marginTop: 16, gap: 12, flexWrap:'wrap'
            }}>
              <div style={{display:'inline-flex', alignItems:'center', gap: 8, fontSize: 13, color:'var(--red)'}}>
                <span style={{
                  width: 6, height: 6, borderRadius:'50%', background:'var(--red)',
                  boxShadow:'0 0 0 3px rgba(204,46,59,0.12)'
                }}/>
                <span style={{fontWeight: 600}}>75 hours / month, every month</span>
              </div>
              <div style={{fontSize:12, color:'var(--ink-4)'}}>No audit trail. Re-keyed by hand.</div>
            </div>
          </div>

          {/* Right: Auto-Council clean */}
          <div>
            <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom: 14}}>
              <div style={{display:'flex', alignItems:'center', gap:8}}>
                <IconLogo size={16} />
                <span style={{fontSize:13, color:'var(--ink-3)'}}>April 2026 · Skeda tal-Ħlasijiet</span>
              </div>
              <span className="tag green">Auto-generated</span>
            </div>

            <div style={{border:'1px solid var(--hairline)', borderRadius: 12, overflow:'hidden', background:'#fff'}}>
              <table className="skeda">
                <thead>
                  <tr>
                    <th style={{width:30}}>#</th>
                    <th>Supplier</th>
                    <th style={{width:62}}>M·Req</th>
                    <th style={{width:54}}>P·M</th>
                    <th className="right" style={{width:86}}>Total</th>
                  </tr>
                </thead>
                <tbody>
                  {HERO_INVOICES.map((inv, i) => (
                    <tr key={i}>
                      <td className="mono text-ink4">{String(i+1).padStart(2,'0')}</td>
                      <td>{inv.supplier}</td>
                      <td><span className="tag">{inv.mreq}</span></td>
                      <td><span className="tag soft">{inv.pm}</span></td>
                      <td className="right" style={{fontWeight:600}}>{fmtMoney(inv.amount + inv.vat)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            <div className="row gap-16 mt-16" style={{flexWrap:'wrap'}}>
              <div className="row gap-8 ai-c" style={{fontSize: 13, color:'var(--ink-3)'}}>
                <IconCheck size={14} color="var(--green)" /> Codes assigned automatically
              </div>
              <div className="row gap-8 ai-c" style={{fontSize: 13, color:'var(--ink-3)'}}>
                <IconCheck size={14} color="var(--green)" /> Audit trail per line
              </div>
              <div className="row gap-8 ai-c" style={{fontSize: 13, color:'var(--ink-3)'}}>
                <IconCheck size={14} color="var(--green)" /> Ready to export
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Nav, Hero, ProblemSection, Wordmark, HEADLINES });
