/* global React, HeroPlate, PillarDiagram, CorridorsDiagram, CorridorSchematic, Reveal, LITMUS_DATA */
const useStateH = React.useState;
const useEffectH = React.useEffect;

const HERO_HEADLINES = [
  { h: ["We invest in the operating ", "infrastructure", " of growth markets."], accent: 1 },
  { h: ["Backing the rails of ", "everyday economic", " life."], accent: 1 },
  { h: ["Infrastructure for economies being ", "rebuilt", " in real time."], accent: 1 },
];

function Home({ mapOn, headlineIdx, setPage }) {
  const headline = HERO_HEADLINES[headlineIdx];
  const headlineKey = `${headlineIdx}`; // re-mount on change to retrigger scribe
  return (
    <main>
      {/* HERO */}
      <section className="hero" data-screen-label="01 Home · Hero" style={{paddingTop:120}}>
        <div className="container">
          <div className="hero-grid">
            <div>
              <div className="eyebrow eyebrow-fade" style={{color:'var(--teal)'}}>LITMUS · Fund II · 2026</div>
              <h1 className="hero-h1" key={headlineKey}>
                {headline.h.map((part, i) => {
                  if (i === headline.accent) {
                    return <em key={i} className="hero-accent" style={{'--scribe-d': `${250 + i*120}ms`}}>{part}</em>;
                  }
                  // Word-by-word reveal for non-accent parts
                  const words = part.split(/(\s+)/);
                  return <span key={i}>{words.map((w, wi) => {
                    if (/^\s+$/.test(w)) return <span key={wi}>{w}</span>;
                    return <span key={wi} className="hero-word" style={{'--w-d': `${i*180 + wi*60}ms`}}>{w}</span>;
                  })}</span>;
                })}
              </h1>
              <p className="sub hero-sub">Financial rails, merchant systems, and essential urban infrastructure — built for the markets where everyday life is being rewired.</p>
              <div className="cta-row hero-cta">
                <a className="btn btn-primary" onClick={() => setPage('thesis')}>Explore our thesis <span className="arrow">→</span></a>
                <a className="btn btn-ghost" onClick={() => setPage('portfolio')}>View portfolio</a>
              </div>
              <div className="hero-tags hero-tags-anim">
                <span style={{'--t-d':'900ms'}}>Financial Rails</span>
                <span style={{'--t-d':'970ms'}}>Merchant Systems</span>
                <span style={{'--t-d':'1040ms'}}>Urban Infrastructure</span>
                <span style={{'--t-d':'1110ms'}}>Essential Services</span>
              </div>
            </div>
            <div className="hero-graphic"><HeroPlate/></div>
          </div>
        </div>
        <div className="hero-marquee-wrap">
          <div className="hero-marquee-label">Selected portfolio · Fund II</div>
          <div className="hero-marquee">
            <div className="hero-marquee-track">
              {[...Array(2)].map((_, k) => (
                <div className="hero-marquee-set" key={k} aria-hidden={k === 1}>
                  {['Ziina', 'Flutterwave', 'Konfío', 'HyperPay', 'M-PESA', 'Aldar', 'Talabat', 'PayU', 'F&N', 'Careem', 'BJC', 'MaxAB'].map(n => (
                    <span key={n} className="metallic-shine">{n}</span>
                  ))}
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* NETWORK STRIP */}
      <div className="network-strip" data-screen-label="02 Home · Backers">
        <div className="container">
          <div className="label">Strategic network across energy, property, distribution &amp; consumer staples</div>
          <div className="logos">
            {LITMUS_DATA.backersMain.map(b => (
              <div className="logo-cell" key={b.name}>
                {b.name}
                <span className="sub">{b.tag}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* DAILY ECONOMY CROSS-SECTION */}
      <CrossSection/>

      {/* THESIS PILLARS */}
      <section data-screen-label="04 Home · Thesis Pillars">
        <div className="container">
          <div className="section-head">
            <div>
              <div className="eyebrow">§ Thesis · Three pillars</div>
              <h2>We invest across three layers of the real economy.</h2>
            </div>
            <a onClick={() => setPage('thesis')} style={{cursor:'pointer', borderBottom:'1px solid currentColor', paddingBottom:4, fontSize:14}}>Read the thesis →</a>
          </div>
          <div className="pillars">
            <div className="pillar reveal">
              <div className="diagram"><PillarDiagram kind="rails"/></div>
              <div className="num">01 / Financial Rails</div>
              <h3>Payments, wallets, settlement &amp; cross-border money movement.</h3>
              <p>The pipes underneath every transaction — from mobile wallets to acquiring, merchant finance, and corridor-level clearing.</p>
              <div className="companies">
                <span>Ziina</span><span>HyperPay</span><span>PayU</span><span>Flutterwave</span><span>M-PESA</span>
              </div>
            </div>
            <div className="pillar reveal">
              <div className="diagram"><PillarDiagram kind="commerce"/></div>
              <div className="num">02 / Merchant Systems</div>
              <h3>Delivery, SMB operating tools, merchant enablement &amp; local commerce.</h3>
              <p>Software and credit for the storefronts, operators and last-mile teams who actually move goods in high-growth cities.</p>
              <div className="companies">
                <span>Mrsool</span><span>Konfío</span><span>Bukalapak</span>
              </div>
            </div>
            <div className="pillar reveal">
              <div className="diagram"><PillarDiagram kind="urban"/></div>
              <div className="num">03 / Urban &amp; Consumer Infrastructure</div>
              <h3>Energy, real estate, mobility &amp; consumer distribution.</h3>
              <p>The physical operating layer: power, lifestyle real estate, mobility and the staples supply chain that reaches every storefront.</p>
              <div className="companies">
                <span>ACWA Power</span><span>ADNOC Dist.</span><span>Majid Al Futtaim</span><span>F&amp;N</span>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* STATS */}
      <section style={{paddingTop:0, paddingBottom:0}} data-screen-label="05 Home · Stats">
        <div className="container" style={{paddingTop:0}}>
          <div className="stats">
            <div className="stat"><div className="val">US$ 102<em>M</em></div><div className="lbl">Assets under management</div></div>
            <div className="stat"><div className="val">04<em></em></div><div className="lbl">Growth corridors</div></div>
            <div className="stat"><div className="val">13<em></em></div><div className="lbl">Active portfolio companies</div></div>
            <div className="stat"><div className="val">08<em></em></div><div className="lbl">Operator-network partners</div></div>
          </div>
        </div>
      </section>

      {/* PORTFOLIO */}
      <section data-screen-label="06 Home · Portfolio">
        <div className="container">
          <div className="section-head">
            <div>
              <div className="eyebrow">§ Portfolio · Selected</div>
              <h2>Companies building the operating layer.</h2>
            </div>
            <a onClick={() => setPage('portfolio')} style={{cursor:'pointer', borderBottom:'1px solid currentColor', paddingBottom:4, fontSize:14}}>View all 13 →</a>
          </div>
          <div className="portfolio-grid">
            {LITMUS_DATA.portfolioFeatured.map(c => (
              <div className="pf-card metallic-hover-trigger" key={c.name}>
                <div>
                  <div className="pf-logo metallic-hover">{c.name}</div>
                  <div className="pf-meta"><span>{c.sector}</span><span>{c.region}</span></div>
                  <div className="pf-desc">{c.desc}</div>
                </div>
                <div className="pf-arrow">→</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* CORRIDORS MAP */}
      {mapOn && (
        <section data-screen-label="07 Home · Corridors">
          <div className="container">
            <div className="section-head">
              <div>
                <div className="eyebrow">§ Reach · Growth corridors</div>
                <h2>Connected across growth corridors.</h2>
              </div>
              <p style={{maxWidth:'32ch', fontSize:14, color:'var(--muted)', margin:0}}>Our deals, operator relationships, and research concentrate along corridors where everyday economic life is being rebuilt.</p>
            </div>
            <div className="corridor-schematic-wrap">
              <CorridorSchematic/>
            </div>
          </div>
        </section>
      )}

      {/* INSIGHTS */}
      <section data-screen-label="08 Home · Insights">
        <div className="container">
          <div className="section-head">
            <div>
              <div className="eyebrow">§ Insights</div>
              <h2>How we read the operating layer.</h2>
            </div>
            <a onClick={() => setPage('insights')} style={{cursor:'pointer', borderBottom:'1px solid currentColor', paddingBottom:4, fontSize:14}}>All insights →</a>
          </div>
          <div className="insights-grid">
            {LITMUS_DATA.insights.slice(0,5).map((it, i) => (
              <div key={i} className={`insight ${it.featured ? 'featured' : ''}`} onClick={()=>setPage('insights')}>
                <div>
                  <div className="kicker">{it.kicker}</div>
                  <h4>{it.title}</h4>
                </div>
                <div className="meta">{it.meta}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* CONTACT */}
      <section data-screen-label="09 Home · Contact">
        <div className="container">
          <ContactForm/>
        </div>
      </section>
    </main>
  );
}

function CrossSection() {
  const [active, setActive] = useStateH(0);
  const layers = LITMUS_DATA.layers;
  const cur = layers[active];
  return (
    <section data-screen-label="03 Home · Cross-section">
      <div className="container">
        <div className="section-head">
          <div>
            <div className="eyebrow">§ Daily economy · Cross-section</div>
            <h2>One transaction, five operating layers.</h2>
          </div>
          <p style={{maxWidth:'34ch', fontSize:14, color:'var(--muted)', margin:0}}>Pour a coffee in Dubai, ride a scooter in Bangkok, or pay a vendor in Lagos — the same five layers move underneath. We invest across all of them.</p>
        </div>
        <div className="cross-section">
          <div className="cross-stack">
            <div className="layer-card">
              {layers.map((l, i) => (
                <div key={l.num} className={`layer-row ${active===i?'active':''}`} onClick={()=>setActive(i)}>
                  <span className="lr-num">{l.num}</span>
                  <span className="lr-title">{l.title}</span>
                  <span className="lr-mark">{l.mark}</span>
                </div>
              ))}
            </div>
          </div>
          <div className="cross-narrative">
            <div className="cross-step" key={cur.num}>
              <div className="eyebrow">Layer {cur.num}</div>
              <h3>{cur.title}</h3>
              <p>{cur.body}</p>
              <div className="ex">{cur.ex.map(e => <span key={e}>{e}</span>)}</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// TODO: Replace with actual Google Form URL before deploy
const PITCH_FORM_URL = 'TODO_GOOGLE_FORM_URL';

function ContactForm() {
  const [form, setForm] = useStateH({ region:'Gulf', sector:'Financial Rails', stage:'Seed' });

  return (
    <div className="contact-wrap">
      <div>
        <div className="eyebrow" style={{color:'var(--teal)'}}>§ Pitch us</div>
        <h2>Building operating infrastructure for growth markets?</h2>
        <p>We'd like to hear from you. Pitches are read by our investment team directly — no intro required.</p>
        <FitWizard form={form} setForm={setForm}/>
        <div style={{marginTop:28, fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.14em', color:'var(--muted)'}}>
          <div style={{marginBottom:10}}>→ hello@litmus.capital</div>
          <div>→ Dubai · Singapore · Lagos · México DF</div>
        </div>
      </div>
      <div>
        <h4 style={{fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.16em', textTransform:'uppercase', color:'var(--teal)', margin:'0 0 24px', fontWeight:500}}>02 / Pitch form</h4>
        <div style={{padding:32, border:'1px solid var(--border)', borderRadius:12}}>
          <p style={{margin:'0 0 24px', lineHeight:1.6, color:'var(--muted)'}}>
            Send your pitch through our intake form. A partner will read it directly — confidential, reviewed within five business days.
          </p>
          <div className="form-submit">
            <a href={PITCH_FORM_URL} target="_blank" rel="noopener noreferrer" className="btn btn-primary">
              Open pitch form <span className="arrow">→</span>
            </a>
            <span style={{fontFamily:'var(--mono)', fontSize:10, letterSpacing:'0.12em', color:'var(--muted)', textTransform:'uppercase'}}>Confidential · Reviewed within 5 days</span>
          </div>
        </div>
      </div>
    </div>
  );
}

function FitWizard({ form, setForm }) {
  const sectors = ['Financial Rails', 'Merchant Systems', 'Consumer Credit', 'Trust & Community', 'Digital Entertainment', 'Other'];
  const regions = ['Gulf', 'Africa', 'SE Asia', 'LatAm', 'Europe adj.', 'Other'];
  const stages  = ['Pre-seed', 'Seed', 'Series A', 'Series B', 'Series C+'];

  const sectorFit = ['Financial Rails','Merchant Systems'].includes(form.sector) ? 'strong'
                  : ['Consumer Credit','Trust & Community'].includes(form.sector) ? 'adjacent'
                  : form.sector === 'Other' ? null : 'adjacent';
  const stageFit = ['Seed','Series A','Series B'].includes(form.stage) ? 'strong'
                 : ['Series C+'].includes(form.stage) ? 'adjacent' : 'adjacent';

  let result = null;
  if (form.sector && form.region && form.stage) {
    if (sectorFit === 'strong' && stageFit === 'strong') {
      result = { tone:'strong', badge:'Strong fit', h:'This is squarely on thesis.', p:'A partner will read your pitch the week it lands. Expect a response within five business days.' };
    } else if (sectorFit === 'adjacent' || stageFit === 'adjacent') {
      result = { tone:'adjacent', badge:'Adjacent fit', h:'Worth a conversation.', p:'You sit on the edge of our active mandate. We will respond — and may route you to a partner in our network if it is a better home.' };
    } else {
      result = { tone:'adjacent', badge:'Out of mandate', h:'We may not be the right home.', p:'You can still send the pitch. We will not waste your cycle if we cannot underwrite — and we will say so plainly.' };
    }
  }

  return (
    <div className="fit-wizard" style={{marginTop:36}}>
      <h4 style={{margin:0}}>01 / Founder Fit</h4>
      <p style={{color:'var(--muted)', fontSize:13, margin:'8px 0 24px', lineHeight:1.55}}>Three answers before you send. Tells you — and us — whether we're the right home.</p>
      <div className="fit-step">
        <span className="lbl">Sector</span>
        <div className="fit-options">
          {sectors.map(x => <span key={x} className={`fit-option ${form.sector===x?'active':''}`} onClick={()=>setForm(f=>({...f,sector:x}))}>{x}</span>)}
        </div>
      </div>
      <div className="fit-step">
        <span className="lbl">Region</span>
        <div className="fit-options">
          {regions.map(x => <span key={x} className={`fit-option ${form.region===x?'active':''}`} onClick={()=>setForm(f=>({...f,region:x}))}>{x}</span>)}
        </div>
      </div>
      <div className="fit-step">
        <span className="lbl">Stage</span>
        <div className="fit-options">
          {stages.map(x => <span key={x} className={`fit-option ${form.stage===x?'active':''}`} onClick={()=>setForm(f=>({...f,stage:x}))}>{x}</span>)}
        </div>
      </div>
      {result && (
        <div className={`fit-result ${result.tone}`}>
          <div className="badge">→ {result.badge}</div>
          <h5>{result.h}</h5>
          <p>{result.p}</p>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Home, ContactForm, CrossSection, FitWizard });
