/* home-sections.jsx — extra home-page sections (compare, benefits, FAQ, partner search).
   Adapted from the cashgo reference into Gigi's brand: warm sand, lime/ink, photography-free. */
const { Icon } = window.GigiMoneyDesignSystem_b54949;

/* ── Compare & check — rate comparison chart ── */
function Compare() {
  const MAX = 100;
  const data = [
    { label: 'Rent advance', v: 18, cls: 'win', logo: true },
    { label: 'Bank Loan', v: 50, cls: 'mid' },
    { label: 'Digital loans', v: 100, cls: 'mid' },
  ];
  const lines = [0, 10, 20,30, 40,  50, 60, 70, 80, 90, 100];
  return (
    <section className="block" id="compare">
      <div className="wrap compare-grid">
        <div>
          <div className="sec-head">
            <span className="eyebrow"><span className="dot" /> Compare and check</span>
            <h2>Those who compare, choose Gigi.</h2>
            <p>When you compare the options side by side, a rent advance is usually the gentlest on your budget. It&rsquo;s a calm way to settle a debt or fix up a property, at the lowest rates on the market.</p>
          </div>
          <button className="btn btn-pill btn-lg" style={{ marginTop: 28 }} onClick={() => window.gScrollToId('simulate')}>Simulate now</button>
        </div>

        <div className="chart">
          <div className="plot">
            {lines.map(v => (
              <div className="gridline" key={v} style={{ bottom: `${v / MAX * 100}%` }}><span>{v}%</span></div>
            ))}
            <div className="bars">
              {data.map(d => (
                <div className={`barcol ${d.cls}`} key={d.label}>
                  {d.logo
                    ? <div className="logo-chip"><span className="m"><Icon name="vault" size={13} /></span><span>Gigi</span></div>
                    : <span className="vtag">{d.v}%</span>}
                  <div className={`bar ${d.cls}`} style={{ height: `${d.v / MAX * 100}%` }} />
                </div>
              ))}
            </div>
          </div>
          <div className="xlabels">
            {data.map(d => <span className={`pill ${d.cls === 'win' ? 'win' : ''}`} key={d.label}>{d.label}</span>)}
          </div>
          <div className="chart-foot">% effective annual rate. An illustrative comparison for a typical facility.</div>
        </div>
      </div>
    </section>
  );
}

/* ── Benefits + Everyone wins ── */
function Benefits() {
  const items = [
    { t: 'Agility', b: 'Run the numbers, get approved, and see the money land in your account within 15 minutes of approval.' },
    { t: 'Practicality', b: 'Sort out your finances without leaving home, and get the money in hand without the paperwork runaround.' },
    { t: 'Security', b: 'Bank-grade protection, titles verified through Ardhi Sasa, real support when you need it, and your data kept private.' },
  ];
  const [active, setActive] = React.useState(0);
  return (
    <section className="block" id="why">
      <div className="wrap benefits-grid">
        <div className="sec-head">
          <h2>We turn the rent you&rsquo;ve already earned into liquidity you can use today.</h2>
          <div className="ben-list">
            {items.map((it, i) => (
              <div className={`ben-item ${active === i ? 'active' : ''}`} key={it.t} onClick={() => setActive(i)}>
                <h3>{it.t}</h3>
                {active === i && <p>{it.b}</p>}
                <div className="ul"><i /></div>
              </div>
            ))}
          </div>
        </div>

        <div className="ben-visual">
          <div className="ben-card">
            <div className="glow" />
            <div className="top">
              <span className="badge">Released</span>
              <span className="seal"><Icon name="check" size={18} stroke={2.6} /></span>
            </div>
            <div className="ttl">Advance disbursed</div>
            <div className="sub">Your rent advance has been approved.</div>
            <div className="amt">KES 5,508,000</div>
            <div className="dest">Sent to M-Pesa ····0084</div>
            <div className="line" />
            <div className="row"><span className="ic"><Icon name="clock" size={15} /></span> Money in your account within 15 minutes</div>
            <div style={{ height: 12 }} />
            <div className="row"><span className="ic"><Icon name="sync" size={15} /></span> Repaid automatically from collected rent</div>
          </div>
        </div>
      </div>

      <div className="wrap" style={{ marginTop: 76 }}>
        <div className="everyone">
          <span className="eyebrow" style={{ display: 'inline-flex' }}><span className="dot" /> Everyone wins</span>
          <h2 style={{ fontFamily: 'var(--fd)', fontWeight: 700, fontSize: 'clamp(28px,3.4vw,40px)', letterSpacing: '-.02em', margin: '14px 0 0' }}>Rent prepayment pays off for everyone.</h2>
          <p style={{ margin: '14px 0 0', fontSize: 17, lineHeight: 1.55, color: 'var(--ink-2)' }}>Whoever you are, Gigi is built around your cash flow, benefiting the owners who unlock liquidity and the managers who serve them.</p>
        </div>
        <div className="wf2-grid">
          <div className="wf2-col"><span className="wf2-ic"><Icon name="home" size={32} /></span><h3 className="wf2-t">Private property owners</h3><p className="wf2-d">Private property owners, even with one rental, use <b>advance liquidity</b> for school fees, a renovation, or everyday costs, with no debt.</p></div>
          <div className="wf2-col"><span className="wf2-ic"><Icon name="box" size={32} /></span><h3 className="wf2-t">Multi-property owners</h3><p className="wf2-d">Owners with several units bring <b>future rent forward</b> to fund new properties or renovations across a growing portfolio.</p></div>
          <div className="wf2-col"><span className="wf2-ic"><Icon name="bank" size={32} /></span><h3 className="wf2-t">Investors &amp; developers</h3><p className="wf2-d">Investors and real estate companies tap <b>advance liquidity</b> to move on new income-generating assets and land deals.</p></div>
          <div className="wf2-col"><span className="wf2-ic"><Icon name="users" size={32} /></span><h3 className="wf2-t">Property managers &amp; Real estate agencies</h3><p className="wf2-d">Agents offer <b>advance liquidity</b> to their property owners to improve cash flow, and earn referral income on every funded deal.</p></div>
        </div>
      </div>
    </section>
  );
}

/* ── "Moments of clarity" — witty Q&A carousel with arched portraits ── */
function FAQ() {
  const slides = [
    {
      id: 'clarity-advance',
      quote: 'So I can spend next year\u2019s rent\u2026 this year?',
      q: 'What\u2019s a rent advance?',
      a: 'Pretty much. You bring up to 24 months of future rent forward as one lump sum today. No new debt, and the title never leaves your name.',
      link: ['See how it works', 'rent-advance.html'],
      img: 'img/clarity-advance.png',
    },
    {
      id: 'clarity-guarantee',
      quote: 'Wait, I get paid even when my tenant ghosts me?',
      q: 'What\u2019s rent guarantee?',
      a: 'Yep. Your tenant pays a small monthly fee instead of a deposit, and your rent lands on time every month. If someone falls behind, chasing it becomes our job, not yours.',
      link: ['Meet rent guarantee', 'rent-guarantee.html'],
      img: 'img/clarity-guarantee.png',
    },
    {
      id: 'clarity-heloc',
      quote: 'It\u2019s like a credit card backed by my buildings. Except the limit is actually useful.',
      q: 'What\u2019s a HELOC?',
      a: 'Exactly. A revolving credit line backed by your property equity, serviced by the rent you already collect. Draw on it when you need, repay as rent comes in.',
      link: ['Explore the HELOC', 'heloc.html'],
      img: 'img/clarity-heloc.png',
    },
  ];
  const [idx, setIdx] = React.useState(0);
  const n = slides.length;
  const s = slides[idx];
  const next = (idx + 1) % n;
  const prev = (idx - 1 + n) % n;
  const goNext = () => setIdx(next);
  const goPrev = () => setIdx(prev);

  return (
    <section className="block clarity" id="faq">
      <div className="dots" aria-hidden="true" />
      <div className="wrap clarity-grid">
        <div className="clarity-card">
          <div className="cc-arch">
            <img src={s.img} alt={s.q} style={{ display: 'block', width: '100%', height: '330px', objectFit: 'cover' }} />
          </div>
          <div className="cc-panel">
            <span className="cc-pill">{s.q}</span>
            <p className="cc-body">{s.a}</p>
            <a className="cc-link" href={s.link[1]}>{s.link[0]} <Icon name="chevR" size={15} /></a>
          </div>
        </div>

        <div className="clarity-q">
          <div className="clarity-eyebrow">We hear your questions, and your moments of clarity.</div>
          <blockquote className="clarity-quote">&ldquo;{s.quote}&rdquo;</blockquote>
          <div className="clarity-nav">
            <button className="prev" onClick={goPrev} aria-label="Previous question"><Icon name="chevL" size={20} stroke={2.2} /></button>
            <button className="next" onClick={goNext}>{slides[next].q} <Icon name="chevR" size={18} stroke={2.2} /></button>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ── Partner search ──
   Looks up the Gigi partner directory via the `partnerSearch` Cloud Function
   (the `partners` collection is server-only, so this is the only way to read
   it). Override the endpoint with window.GIGI_PARTNERS_ENDPOINT for the local
   emulator. */
const PARTNERS_ENDPOINT = () =>
  window.GIGI_PARTNERS_ENDPOINT || 'https://africa-south1-gigi-money.cloudfunctions.net/partnerSearch';

function PartnerSearch() {
  const [q, setQ] = React.useState('');
  const [res, setRes] = React.useState(null);   // { name, partners } once a search resolves
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');
  const reqId = React.useRef(0);                 // guards against out-of-order responses

  const search = async () => {
    const v = q.trim();
    setError('');
    if (v.length < 2) { setRes(null); return; }
    const id = ++reqId.current;
    setLoading(true);
    try {
      // App Check attestation (anti-bot / anti-replay); null until configured.
      const appCheck = window.gigiAppCheckToken ? await window.gigiAppCheckToken() : null;
      const r = await fetch(`${PARTNERS_ENDPOINT()}?q=${encodeURIComponent(v)}`,
        appCheck ? { headers: { 'X-Firebase-AppCheck': appCheck } } : undefined);
      const data = await r.json().catch(() => ({}));
      if (id !== reqId.current) return;          // a newer search superseded this one
      if (!r.ok || !data.ok) throw new Error(data.error || 'Could not run the search.');
      setRes({ name: v, partners: Array.isArray(data.partners) ? data.partners : [] });
    } catch (e) {
      if (id !== reqId.current) return;
      setError(e.message || 'Could not run the search. Please try again.');
      setRes(null);
    } finally {
      if (id === reqId.current) setLoading(false);
    }
  };
  const onKey = (e) => { if (e.key === 'Enter') search(); };
  const found = res && res.partners.length > 0;
  return (
    <section className="block" id="partner-search">
      <div className="wrap">
        <div className="psearch">
          <h2>See if your property manager is already a Gigi partner.</h2>
          <div className="ps-form">
            <input value={q} onChange={e => setQ(e.target.value)} onKeyDown={onKey} placeholder="Enter the name of your property manager or agency" aria-label="Property manager name" />
            <button className="btn btn-pill btn-lg" onClick={search} disabled={loading}>{loading ? 'Searching…' : 'Search'}</button>
          </div>
          {error && (
            <div className="ps-result miss">
              <span className="ic"><Icon name="info" size={18} stroke={2.2} /></span>
              <p>{error}</p>
            </div>
          )}
          {!error && res && (
            <div className={`ps-result ${found ? 'found' : 'miss'}`}>
              <span className="ic"><Icon name={found ? 'check' : 'info'} size={18} stroke={2.2} /></span>
              {found
                ? <p><b>Good news.</b> {res.partners.length === 1
                    ? <>&ldquo;{res.partners[0].name}&rdquo;{res.partners[0].city ? ` (${res.partners[0].city})` : ''} already works with Gigi.</>
                    : <>We found {res.partners.length} partners matching &ldquo;{res.name}&rdquo;: {res.partners.map((p, i) => <React.Fragment key={p.name}>{i ? ', ' : ''}<b>{p.name}</b>{p.city ? ` (${p.city})` : ''}</React.Fragment>)}.</>
                  } Run a simulation and your advance can be verified faster.</p>
                : <p>We couldn&rsquo;t find “{res.name}” yet. Onboard directly, or <a href="index.html#partner">invite them to partner</a> with Gigi.</p>}
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

/* ── Representative cost example ── */
function RepExample() {
  const rows = [
    ['You assign', '6 months of rent'],
    ['Monthly rent', 'KES 250,000'],
    ['Gross future rent', 'KES 1,500,000'],
    ['Discount', '– KES 135,000'],
  ];
  return (
    <section className="block" id="pricing">
      <div className="wrap rep-grid">
        <div className="sec-head">
          <span className="eyebrow"><span className="dot" /> Clear, upfront pricing</span>
          <h2>No surprises. Here&rsquo;s exactly what it costs.</h2>
          <p>Every fee is shown before you agree. The only cost is the discount, set by the cost of funding and the risk of the tenancy. Nothing hidden, no monthly account fees.</p>
        </div>
        <div className="rep-card">
          <div className="rep-tag">A representative example</div>
          <div className="rep-rows">
            {rows.map(([k, v]) => (
              <div className="rep-row" key={k}><span>{k}</span><span className="rep-v">{v}</span></div>
            ))}
          </div>
          <div className="rep-out">
            <div>
              <div className="rep-out-k">You receive today</div>
              <div className="rep-out-v">KES 1,365,000</div>
            </div>
            <div className="rep-rate">9.0%<small>total cost over 6 months</small></div>
          </div>
          <p className="rep-fine">Illustrative only. Your rate depends on the verified rent and tenancy. Subject to eligibility and verified ownership via Ardhi&nbsp;Sasa.</p>
        </div>
      </div>
    </section>
  );
}

/* ── Testimonials ── */
function Testimonials() {
  const items = [
    { q: 'I brought six months of rent forward and finished the renovation without touching my savings. The money was in M-Pesa the same afternoon.', n: 'James Meco', r: 'Apartment owner · Westlands, Nairobi', i: 'JM' },
    { q: 'A tenant went quiet for two months and I didn\u2019t feel a thing. Rent guarantee paid on schedule and Gigi handled the chasing.', n: 'Susan Karanja', r: 'Family trust · Mombasa', i: 'SK' },
    { q: 'The equity line is the first facility that actually understood my buildings. Drawing down and repaying from rent just makes sense.', n: 'Aisha Mohamed', r: 'Property owner · Kilimani', i: 'AM' },
  ];
  return (
    <section className="block" id="testimonials" style={{ paddingTop: 30 }}>
      <div className="wrap">
        <div className="sec-head">
          <span className="eyebrow"><span className="dot" /> Loved by property owners</span>
          <h2>Trusted by property owners across Kenya.</h2>
        </div>
        <div className="tcards">
          {items.map(t => (
            <figure className="tcard" key={t.n}>
              <div className="tstars" aria-label="5 out of 5">
                {[0, 1, 2, 3, 4].map(i => <Icon key={i} name="check" size={13} stroke={2.6} />)}
              </div>
              <blockquote>&ldquo;{t.q}&rdquo;</blockquote>
              <figcaption>
                <span className="tavatar">{t.i}</span>
                <span><span className="tname">{t.n}</span><span className="trole">{t.r}</span></span>
              </figcaption>
            </figure>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ── Trust / compliance band ── */
function Compliance() {
  const items = [
    ['shield', 'Licensed & regulated', 'We operate as a licensed and regulated business.'],
    ['lock', 'Your data, protected', 'Registered with the ODPC and secured with bank-grade encryption.'],
    ['ardhi', 'Ownership verified', 'Every title confirmed against the national registry via Ardhi Sasa.'],
    ['sync', 'Serviced transparently', 'Repaid from collected rent, with every fee shown before you agree.'],
  ];
  return (
    <section className="block" id="trust" style={{ paddingTop: 20 }}>
      <div className="wrap">
        <div className="compliance">
          <div className="compliance-head">
            <span className="eyebrow"><span className="dot" /> Built to be trusted</span>
            <h3>Safe hands for your property and your rent.</h3>
          </div>
          <div className="compliance-grid">
            {items.map(([ic, t, b]) => (
              <div className="compliance-item" key={t}>
                <span className="ci"><Icon name={ic} size={20} /></span>
                <div className="ct">{t}</div>
                <p>{b}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ── Who it's for (audience segments) ── */
function WhoFor() {
  const cards = [
    { ic: 'home', t: 'Property owners', href: 'rent-advance.html#prequalify',
      d: 'Property owners, even with one rental, use <b>advance liquidity</b> for school fees, a renovation, or everyday costs, with no debt.' },
    { ic: 'box', t: 'Multi-property owners', href: 'rent-advance.html#prequalify',
      d: 'Owners with several units bring <b>future rent forward</b> to fund new properties or renovations across a growing portfolio.' },
    { ic: 'bank', t: 'Investors & developers', href: 'heloc.html#prequalify',
      d: 'Investors and real estate companies tap <b>advance liquidity</b> to move on new income-generating assets and land deals.' },
    { ic: 'users', t: 'Property managers', href: 'index.html#partner',
      d: 'Agents offer <b>advance liquidity</b> to their property owner clients to improve cash flow, and earn referral income on every funded deal.' },
  ];
  return (
    <section className="block" id="who" style={{ paddingTop: 30 }}>
      <div className="wrap">
        <div className="sec-head">
          <span className="eyebrow"><span className="dot" /> Who it&rsquo;s for</span>
          <h2>Who is a Gigi rent advance for?</h2>
          <p>Whether you own one unit or fifty, Gigi is built around your cash flow.</p>
        </div>
        <div className="wf2-grid">
          {cards.map(c => (
            <div className="wf2-col" key={c.t}>
              <span className="wf2-ic"><Icon name={c.ic} size={32} /></span>
              <h3 className="wf2-t">{c.t}</h3>
              <p className="wf2-d" dangerouslySetInnerHTML={{ __html: c.d }} />
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { GCompare: Compare, GBenefits: Benefits, GFAQ: FAQ, GPartnerSearch: PartnerSearch, GRepExample: RepExample, GTestimonials: Testimonials, GCompliance: Compliance, GWhoFor: WhoFor });
