// ============================================================
// Dhobify landing v2 — FAQ, Final CTA, Footer, SmartBanner
// Depends on _lib.jsx
// ============================================================

const {
  DHB_T: T3, DHB_MAX: MAX3, DHB_PADD: PADD3, DHB_PADM: PADM3, DHB_STORE: STORE3,
  dhbTrack: track3,
  useReducedMotion: useRM3, useReveal: useReveal3,
  IcCheck: IcCheck3, IcChev: IcChev3, IcArrow: IcArrow3, IcInsta: IcInsta3, IcWA: IcWA3, IcX_logo: IcXlogo3,
  DhbMark: Mark3, DhbWordmark: Word3,
  DhbButton: Btn3, DhbStoreBadge: Badge3, DhbEyebrow: Eb3, DhbHeadline: H3, DhbHighlight: Hl3,
  DhbReveal: Rv3, DhbContainer: Cont3, DhbDotGrid: Dot3,
  DhbQR: QR3,
} = window;

// ============================================================
// FAQ
// ============================================================
const FAQ = [
  { id: 'where',    q: 'Where do you operate?',
    a: `Currently in Baner, Pune. Aundh, Wakad, and Hinjewadi are opening soon. Tap "Join the waitlist" in the app if you live there — we'll text you when we go live.` },
  { id: 'pickup',   q: 'How long does a pickup take?',
    a: `Most pickups in central Pune happen within 30 minutes of your booking. The exact ETA shows in the app before you confirm — and the live status keeps you honest on it.` },
  { id: 'damage',   q: 'What if my dhobi is rude or my items come back damaged?',
    a: `Tell us via in-app support. We investigate every complaint within 24 hours and refund or re-do the order when the fault is ours or the dhobi's. Dhobis with repeat issues get removed.` },
  { id: 'cash',     q: 'Can I pay in cash?',
    a: `Yes. Cash, UPI, or card — your choice, at delivery. We never hold your money.` },
  { id: 'dryclean', q: 'Do you handle dry-cleaning?',
    a: `Yes. Most dhobis on the platform offer wash, iron, dry-clean, and special-care items like sarees, suits, and curtains.` },
  { id: 'verify',   q: 'How are dhobis verified?',
    a: `We meet them in person, check their shop, verify their phone and bank details, and approve them only after a test order. Every listing has a "Verified by Dhobify" badge for a reason.` },
  { id: 'delicate', q: 'What about delicate or expensive clothes?',
    a: `Mark them as "special care" during booking. The dhobi will confirm before accepting and quote a price separately. You can decline before they pick up.` },
  { id: 'home',     q: 'Do I need to be home for pickup?',
    a: `No. Leave the bag with your watchman or at your door — we'll send a photo confirmation when the dhobi picks it up.` },
  { id: 'rate',     q: 'How does pricing actually work?',
    a: `Each dhobi sets their own per-item rates. You see them before booking. Your dhobi keeps 100% of what you pay — Dhobify takes no commission. Dhobis pay a flat monthly subscription for the app (free while we launch). No platform charge, no surge, no minimum.` },
  { id: 'cancel',   q: 'What if I need to cancel?',
    a: `Free cancellation up until the dhobi accepts the order. After that, cancel within 5 minutes of acceptance for free; later cancellations are 50% of the estimate to compensate the dhobi for the trip.` },
];

function FaqItem({ item, open, onToggle, order = 0 }) {
  // Per-item staggered entrance, independent of the parent reveal.
  const [ref, visible] = useReveal3();
  return (
    <div ref={ref} style={{
      borderBottom: `1px solid ${T3.border}`,
      opacity: visible ? 1 : 0,
      transform: visible ? 'translateY(0)' : 'translateY(10px)',
      transition: `opacity .5s ease ${order * 45}ms, transform .5s cubic-bezier(.16,1,.3,1) ${order * 45}ms`,
    }}>
      <button onClick={onToggle} aria-expanded={open} style={{
        width: '100%', textAlign: 'left',
        padding: '20px 0',
        background: 'transparent', border: 'none', cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        gap: 16, color: T3.ink,
      }}>
        <span style={{
          fontSize: 17, fontWeight: 700, letterSpacing: -.3, lineHeight: 1.35,
        }}>{item.q}</span>
        <span style={{
          width: 32, height: 32, borderRadius: 16,
          background: open ? T3.blue : T3.bg,
          color: open ? '#fff' : T3.ink,
          display: 'grid', placeItems: 'center',
          flex: '0 0 auto',
          transition: 'background .25s ease, transform .35s cubic-bezier(.34,1.56,.64,1)',
          transform: open ? 'rotate(180deg)' : 'rotate(0)',
        }}><IcChev3 size={16} stroke={open ? '#fff' : T3.ink} /></span>
      </button>
      {/* Spring open/close via the grid-rows trick — animates to content height */}
      <div style={{
        display: 'grid',
        gridTemplateRows: open ? '1fr' : '0fr',
        opacity: open ? 1 : 0,
        transition: 'grid-template-rows .45s cubic-bezier(.16,1,.3,1), opacity .3s ease',
      }}>
        <div style={{ minHeight: 0, overflow: 'hidden' }}>
          <p style={{
            margin: '0 0 22px', fontSize: 15.5, lineHeight: 1.6,
            color: T3.slate, fontWeight: 500, maxWidth: 760,
            textWrap: 'pretty',
          }}>{item.a}</p>
        </div>
      </div>
    </div>
  );
}

function DhbFAQ({ mobile }) {
  const [open, setOpen] = React.useState('where');
  return (
    <section id="faq" data-screen-label="faq" style={{
      paddingTop: mobile ? 56 : 96,
      paddingBottom: mobile ? 56 : 96,
      background: T3.surface,
      borderTop: `1px solid ${T3.border}`,
      borderBottom: `1px solid ${T3.border}`,
    }}>
      <Cont3 mobile={mobile}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: mobile ? '1fr' : '1fr 2fr',
          gap: mobile ? 32 : 80,
        }}>
          <div>
            <Rv3><Eb3>FAQ</Eb3></Rv3>
            <Rv3 delay={80}>
              <H3 level={2} mobile={mobile} style={{ marginTop: 14 }}>
                Real questions.<br/>Real answers.
              </H3>
            </Rv3>
            <Rv3 delay={140}>
              <p style={{
                margin: '18px 0 0',
                fontSize: 15.5, lineHeight: 1.55,
                color: T3.slate, fontWeight: 500, maxWidth: 360,
                textWrap: 'pretty',
              }}>
                Not seeing yours?{' '}
                <a href="/support"
                  onClick={() => track3('support_link_click', { placement: 'faq' })}
                  style={{ color: T3.blue, fontWeight: 700, textDecoration: 'underline', textUnderlineOffset: 3 }}>
                  Contact us
                </a>
                {' '}— form, email or WhatsApp, your call.
              </p>
            </Rv3>
          </div>
          <Rv3 delay={120}>
            <div>
              {FAQ.map((f, i) => (
                <FaqItem
                  key={f.id} item={f} order={i}
                  open={open === f.id}
                  onToggle={() => {
                    const next = open === f.id ? null : f.id;
                    setOpen(next);
                    if (next) track3('faq_expand', { question_id: f.id });
                  }}
                />
              ))}
            </div>
          </Rv3>
        </div>
      </Cont3>
    </section>
  );
}

// ============================================================
// FINAL CONVERSION BAND
// ============================================================
function DhbFinalCTA({ mobile }) {
  const reduced = useRM3();
  const [hlRef, hlVis] = useReveal3();
  return (
    <section data-screen-label="final-cta" data-dhb-zone="#F4F6FF" style={{
      position: 'relative', overflow: 'hidden',
      paddingTop: mobile ? 72 : 120,
      paddingBottom: mobile ? 72 : 120,
    }}>
      <Dot3 opacity={0.05} />
      {/* Aurora pair behind the closing pitch */}
      <div aria-hidden style={{
        position: 'absolute',
        top: '50%', left: '50%',
        transform: 'translate(-50%, -50%)',
        width: 760, height: 460,
        background: 'radial-gradient(ellipse at center, rgba(61,90,254,0.18) 0%, rgba(61,90,254,0) 70%)',
        filter: 'blur(40px)',
        animation: reduced ? 'none' : 'dhbAuroraA 28s ease-in-out infinite alternate',
        pointerEvents: 'none', zIndex: 0,
      }} />
      <div aria-hidden style={{
        position: 'absolute',
        top: '20%', left: '64%',
        width: 420, height: 320,
        background: 'radial-gradient(ellipse at center, rgba(255,212,59,0.14) 0%, rgba(255,212,59,0) 70%)',
        filter: 'blur(40px)',
        animation: reduced ? 'none' : 'dhbAuroraC 34s ease-in-out infinite alternate',
        pointerEvents: 'none', zIndex: 0,
      }} />
      <Cont3 mobile={mobile} style={{ position: 'relative', zIndex: 1, textAlign: 'center' }}>
        <Rv3>
          <Eb3>Last thing</Eb3>
        </Rv3>
        <Rv3 delay={80}>
          <div ref={hlRef}>
            <H3 level={1} mobile={mobile} style={{
              marginTop: 14,
              maxWidth: 820, margin: '14px auto 0',
              fontSize: mobile ? 36 : 60,
            }}>
              Your next clean load is<br/>
              <Hl3 active={hlVis} drawDelay={450}>two taps</Hl3> away.
            </H3>
          </div>
        </Rv3>
        <Rv3 delay={160}>
          <p style={{
            margin: '20px auto 0',
            fontSize: mobile ? 16 : 18, lineHeight: 1.5,
            color: T3.slate, fontWeight: 500, maxWidth: 520,
            textWrap: 'pretty',
          }}>
            No prepay. No markup. Photo proof on every pickup. UPI on delivery. That's it.
          </p>
        </Rv3>
        <Rv3 delay={240}>
          <div style={{
            marginTop: 32,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            gap: 14, flexWrap: 'wrap',
          }}>
            <a href={STORE3.resident.apple} target="_blank" rel="noreferrer"
              onClick={() => track3('install_click', { platform: 'ios', placement: 'final_band' })}
              style={{ textDecoration: 'none' }}>
              <Badge3 variant="apple" height={56} />
            </a>
            <a href={STORE3.resident.google} target="_blank" rel="noreferrer"
              onClick={() => track3('install_click', { platform: 'android', placement: 'final_band' })}
              style={{ textDecoration: 'none' }}>
              <Badge3 variant="google" height={56} />
            </a>
          </div>
        </Rv3>
        {/* Desktop visitors can't tap a store badge — give them a QR instead */}
        {!mobile &&
        <Rv3 delay={300}>
          <div style={{
            marginTop: 36,
            display: 'inline-flex', alignItems: 'center', gap: 18,
            padding: '16px 22px', borderRadius: 20,
            background: T3.surface,
            border: `1px solid ${T3.border}`,
            boxShadow: '0 18px 40px -28px rgba(15,23,42,.25)',
            textAlign: 'left',
          }}>
            <div style={{
              padding: 8, borderRadius: 12, background: '#fff',
              border: `1px solid ${T3.borderSoft}`, lineHeight: 0,
            }}>
              <QR3 size={104} />
            </div>
            <div>
              <div style={{ fontSize: 15, fontWeight: 800, color: T3.ink, letterSpacing: -.2 }}>
                On your laptop?
              </div>
              <div style={{ fontSize: 13, fontWeight: 600, color: T3.slate, marginTop: 3, maxWidth: 220, lineHeight: 1.45 }}>
                Point your phone camera here — it opens the right store automatically.
              </div>
            </div>
          </div>
        </Rv3>}
        <Rv3 delay={mobile ? 320 : 380}>
          <div style={{
            marginTop: 20,
            fontSize: 12, fontWeight: 700, color: T3.slateLight,
            letterSpacing: .4, textTransform: 'uppercase',
          }}>
            Available on iOS &amp; Android · Currently serving Baner, Pune
          </div>
        </Rv3>
      </Cont3>
    </section>
  );
}

// ============================================================
// FOOTER
// ============================================================
function FCol({ title, children }) {
  return (
    <div>
      <div style={{
        fontSize: 11, fontWeight: 800, color: T3.slate,
        letterSpacing: 1.4, textTransform: 'uppercase', marginBottom: 16,
      }}>{title}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>{children}</div>
    </div>
  );
}
function FLink({ href, children, external }) {
  return (
    <a href={href} target={external ? '_blank' : undefined} rel={external ? 'noreferrer' : undefined} style={{
      color: T3.ink, fontSize: 14, fontWeight: 600,
      textDecoration: 'none', letterSpacing: -.05,
    }}
    onMouseEnter={(e) => { e.currentTarget.style.color = T3.blue; }}
    onMouseLeave={(e) => { e.currentTarget.style.color = T3.ink; }}>
      {children}
    </a>
  );
}

// Footer waitlist. There's no public waitlist endpoint yet, so signups go
// through the (unauthenticated) contact endpoint and land in the admin
// Contact inbox tagged as waitlist entries. Success is only shown when the
// API actually accepted the submission — no fake optimism.
const DHB_API_BASE = 'https://api.dhobify.app/api/v1';

function NewsletterForm() {
  const [email, setEmail] = React.useState('');
  const [state, setState] = React.useState('idle');  // idle | sending | done | error
  const [focus, setFocus] = React.useState(false);
  const submit = async (e) => {
    e.preventDefault();
    if (!email.includes('@')) { setState('error'); return; }
    setState('sending');
    try {
      const r = await fetch(`${DHB_API_BASE}/contact`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
          name: 'Waitlist signup',
          phone: 'not provided',
          email,
          role: 'other',
          subject: 'Service-area waitlist (landing footer)',
          message: `Notify ${email} when Dhobify goes live in their area (Aundh / Wakad / Hinjewadi).`,
        }),
      });
      setState(r.ok ? 'done' : 'error');
    } catch { setState('error'); }
    track3('waitlist_signup', { source: 'footer' });
  };
  return (
    <form onSubmit={submit}
      onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
      style={{
      display: 'flex', alignItems: 'center', gap: 8,
      background: T3.surface, padding: 6,
      border: `1px solid ${focus ? T3.blue : T3.border}`,
      boxShadow: focus ? `0 0 0 4px ${T3.blueWash}` : 'none',
      transition: 'border-color .2s ease, box-shadow .2s ease',
      borderRadius: 999, maxWidth: 420,
    }}>
      <input
        type="email" required value={email}
        onChange={(e) => { setEmail(e.target.value); setState('idle'); }}
        placeholder="you@example.com"
        aria-label="Email address"
        style={{
          flex: 1, minWidth: 0,
          border: 'none', outline: 'none',
          background: 'transparent',
          padding: '8px 14px',
          fontFamily: '"Plus Jakarta Sans", system-ui, sans-serif',
          fontSize: 14, fontWeight: 500, color: T3.ink,
        }}
      />
      <button type="submit" disabled={state === 'sending'} style={{
        height: 38, padding: '0 18px', borderRadius: 999,
        background: state === 'done' ? T3.green : state === 'error' ? T3.red : T3.ink,
        color: '#fff', border: 'none', cursor: 'pointer',
        fontSize: 13, fontWeight: 800, letterSpacing: -.1,
        whiteSpace: 'nowrap',
        transition: 'background .2s ease',
      }}>
        {state === 'done' ? '✓ On the list'
        : state === 'sending' ? 'Sending…'
        : state === 'error' ? 'Didn\'t send — retry'
        : 'Notify me'}
      </button>
    </form>
  );
}

function DhbFooter({ mobile }) {
  return (
    <footer style={{
      background: T3.surface,
      borderTop: `1px solid ${T3.border}`,
      padding: mobile ? `56px ${PADM3}px 32px` : `80px ${PADD3}px 40px`,
    }}>
      <div style={{ maxWidth: MAX3, margin: '0 auto' }}>

        {/* Newsletter + brand row */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: mobile ? '1fr' : '1.4fr 1fr',
          gap: mobile ? 32 : 64,
          paddingBottom: mobile ? 36 : 48,
          borderBottom: `1px solid ${T3.border}`,
        }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
              <Mark3 size={36} />
              <Word3 size={22} />
            </div>
            <p style={{
              margin: 0, maxWidth: 380,
              fontSize: 15, lineHeight: 1.55,
              color: T3.slate, fontWeight: 500,
              textWrap: 'pretty',
            }}>
              India's local laundry, finally online. Vendor-first marketplace, built in Pune.
            </p>
          </div>
          <div>
            <div style={{
              fontSize: 11, fontWeight: 800, color: T3.slate,
              letterSpacing: 1.4, textTransform: 'uppercase', marginBottom: 12,
            }}>Opening near you?</div>
            <p style={{
              margin: '0 0 14px', fontSize: 14, color: T3.ink, fontWeight: 600, maxWidth: 380,
            }}>Get notified when we go live in Aundh, Wakad, Hinjewadi.</p>
            <NewsletterForm />
          </div>
        </div>

        {/* Columns */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: mobile ? '1fr 1fr' : 'repeat(4, 1fr)',
          gap: mobile ? 32 : 48,
          padding: mobile ? '36px 0' : '48px 0',
        }}>
          <FCol title="Product">
            <FLink href="#how">How it works</FLink>
            <FLink href="#pricing">Pricing</FLink>
            <FLink href="#verified">Verified dhobis</FLink>
            <FLink href={STORE3.resident.apple} external>iOS app</FLink>
            <FLink href={STORE3.resident.google} external>Android app</FLink>
          </FCol>
          <FCol title="For Vendors">
            <FLink href="#vendors">Become a partner</FLink>
            <FLink href={STORE3.vendor.apple} external>Vendor app (iOS)</FLink>
            <FLink href={STORE3.vendor.google} external>Vendor app (Android)</FLink>
            <FLink href="https://wa.me/919272346508">WhatsApp us</FLink>
          </FCol>
          <FCol title="Company">
            <FLink href="/support">Contact</FLink>
            <FLink href="mailto:press@dhobify.app">Press</FLink>
            <FLink href="mailto:jobs@dhobify.app">Careers</FLink>
          </FCol>
          <FCol title="Legal">
            <FLink href="/privacy">Privacy</FLink>
            <FLink href="/terms">Terms</FLink>
            <FLink href="/account-deletion">Account deletion</FLink>
            <FLink href="/support">Support</FLink>
          </FCol>
        </div>

        {/* Socials */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12, marginBottom: 28,
        }}>
          {[
            { href: 'https://instagram.com/dhobify',  icon: <IcInsta3 size={18} stroke={T3.ink} />, label: 'Instagram' },
            { href: 'https://wa.me/919272346508',     icon: <IcWA3   size={18} stroke={T3.ink} />, label: 'WhatsApp' },
            { href: 'https://x.com/dhobify',          icon: <IcXlogo3 size={16} stroke={T3.ink} />, label: 'X (Twitter)' },
          ].map((s) => (
            <a key={s.label} href={s.href} target="_blank" rel="noreferrer" aria-label={s.label} style={{
              width: 38, height: 38, borderRadius: 19,
              background: T3.bg, border: `1px solid ${T3.border}`,
              display: 'grid', placeItems: 'center',
              transition: 'background .15s ease, transform .15s ease',
            }}
            onMouseEnter={(e) => { e.currentTarget.style.background = T3.blueWash; e.currentTarget.style.transform = 'translateY(-1px)'; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = T3.bg; e.currentTarget.style.transform = 'translateY(0)'; }}>
              {s.icon}
            </a>
          ))}
        </div>

        {/* Base row */}
        <div style={{
          paddingTop: 24, borderTop: `1px solid ${T3.border}`,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          gap: 12, flexWrap: 'wrap',
        }}>
          <span style={{ fontSize: 12, color: T3.slateLight, fontWeight: 600 }}>
            © 2026 Tanvora Labs Pvt Ltd · Made in Pune · Currently serving Baner.
          </span>
          <span style={{ fontSize: 12, color: T3.slateLight, fontWeight: 600 }}>
            <span style={{ fontFamily: '"JetBrains Mono", ui-monospace, monospace', fontWeight: 700, color: T3.slate }}>v2.0</span> · Phase 1
          </span>
        </div>
      </div>
    </footer>
  );
}

// ============================================================
// SMART APP BANNER (Android only)
// iOS gets Apple's native banner via apple-itunes-app meta tag
// ============================================================
function DhbSmartBanner() {
  const [show, setShow] = React.useState(false);
  React.useEffect(() => {
    if (typeof window === 'undefined') return;
    const ua = window.navigator.userAgent || '';
    const isAndroid = /Android/i.test(ua);
    let dismissed = false;
    try { dismissed = window.sessionStorage.getItem('dhb_banner_dismissed') === '1'; } catch {}
    if (isAndroid && !dismissed) setShow(true);
  }, []);
  if (!show) return null;
  const dismiss = () => {
    try { window.sessionStorage.setItem('dhb_banner_dismissed', '1'); } catch {}
    setShow(false);
  };
  return (
    <div role="region" aria-label="Get the Dhobify app on Google Play" style={{
      width: '100%', background: '#fff',
      borderBottom: `1px solid ${T3.border}`,
      padding: '10px 14px',
      display: 'flex', alignItems: 'center', gap: 10,
      position: 'relative', zIndex: 70,
    }}>
      <button onClick={dismiss} aria-label="Dismiss" style={{
        width: 28, height: 28, borderRadius: 14,
        border: 'none', background: 'transparent',
        color: T3.slate, fontSize: 22, lineHeight: 1, cursor: 'pointer',
        display: 'grid', placeItems: 'center', flex: '0 0 auto',
      }}>×</button>
      <Mark3 size={36} />
      <div style={{ minWidth: 0, flex: 1, lineHeight: 1.25 }}>
        <div style={{ fontSize: 14, fontWeight: 800, color: T3.ink, letterSpacing: -.2 }}>Dhobify</div>
        <div style={{ fontSize: 11, color: T3.slate, fontWeight: 600 }}>Doorstep laundry · Free</div>
        <div style={{ fontSize: 11, color: T3.slateLight, fontWeight: 500 }}>GET — On Google Play</div>
      </div>
      <a href={STORE3.resident.google} target="_blank" rel="noreferrer"
        onClick={() => track3('install_click', { platform: 'android', placement: 'smart_banner' })}
        style={{
        padding: '8px 18px', borderRadius: 999,
        background: T3.blue, color: '#fff',
        fontSize: 13, fontWeight: 800, letterSpacing: .4,
        textTransform: 'uppercase', textDecoration: 'none',
        flex: '0 0 auto',
      }}>Open</a>
    </div>
  );
}

// ============================================================
// SCROLL DEPTH TRACKER (top-level effect)
// ============================================================
function DhbScrollDepth() {
  React.useEffect(() => {
    const milestones = [25, 50, 75, 100];
    const fired = new Set();
    const onScroll = () => {
      const h = document.documentElement;
      const scrolled = (h.scrollTop / (h.scrollHeight - h.clientHeight)) * 100;
      milestones.forEach((m) => {
        if (scrolled >= m && !fired.has(m)) {
          fired.add(m);
          track3(`scroll_depth_${m}`, {});
        }
      });
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return null;
}

// --- export ---------------------------------------------------------
Object.assign(window, {
  DhbFAQ, DhbFinalCTA, DhbFooter, DhbSmartBanner, DhbScrollDepth,
});
