// Landing.jsx — the CallxCall landing page.
// Two artboards share this component, parameterized by `variant`:
//   "human" — human-first hero (creators online now)
//   "ai"    — AI fallback hero (talk instantly, lower price)

const CREATORS = [
  { id: 'r1', name: 'Simran',  tag: 'Listener',  rate: 14, rating: 4.9, calls: 312, hue: 290, live: true  },
  { id: 'k1', name: 'Raj',     tag: 'Funny',     rate: 18, rating: 4.8, calls: 540, hue: 35,  live: true  },
  { id: 'm1', name: 'Tara',    tag: 'Chill',     rate: 12, rating: 4.9, calls: 188, hue: 200, live: true  },
  { id: 'a1', name: 'Zoya',    tag: 'Bold',      rate: 22, rating: 4.7, calls: 421, hue: 12,  live: true  },
  { id: 'n1', name: 'Naina',   tag: 'Listener',  rate: 16, rating: 5.0, calls: 96,  hue: 260, live: false },
  { id: 'j1', name: 'Arjun',   tag: 'Funny',     rate: 20, rating: 4.8, calls: 277, hue: 320, live: true  },
];

// ─── Hero presence orb ─────────────────────────────────────────
function PresenceOrb({ ai }) {
  return (
    <div className="hero-orb-wrap" aria-hidden="true">
      <div className="ripple-stack">
        <span></span><span></span><span></span>
      </div>
      <div className={"hero-orb" + (ai ? " hero-orb-ai" : "")}>
        <div className="hero-orb-inner">
          <Waveform
            bars={9}
            color={ai ? "oklch(0.84 0.14 75)" : "oklch(0.94 0.04 285)"}
            height={32}
          />
        </div>
      </div>
      <div className="hero-orb-count">
        <PulseDot />
        <span>{ai ? '24/7 available' : "Someone's online right now"}</span>
      </div>
    </div>
  );
}

// ─── Top nav ───────────────────────────────────────────────────
function Nav({ variant, onJoin }) {
  return (
    <nav className="nav">
      <div className="nav-left">
        <div className="logo">
          <span className="logo-mark">
            <span></span><span></span><span></span>
          </span>
          <span className="logo-text">CallxCall</span>
        </div>
      </div>
      <div className="nav-mid">
        <a href="#how">How it works</a>
        <a href="#why">Why people pay</a>
        <a href="#earn">Earn</a>
      </div>
      <div className="nav-right">
        <button className="btn btn-ghost" onClick={() => onJoin('creator')}>
          Start earning
        </button>
        <button className="btn btn-primary" onClick={() => onJoin('user')}>
          Join waitlist
        </button>
      </div>
    </nav>
  );
}

// ─── Mode toggle (human / ai) ──────────────────────────────────
function ModeToggle({ value, onChange }) {
  return (
    <div className="mode-toggle">
      <button
        className={"mt-btn" + (value === 'human' ? " mt-active" : "")}
        onClick={() => onChange('human')}
      >
        <Waveform
          bars={4}
          color={value === 'human' ? "oklch(0.96 0.002 270)" : "oklch(0.55 0.005 270)"}
          height={10}
        />
        Talk to people
      </button>
      <button
        className={"mt-btn" + (value === 'ai' ? " mt-active" : "")}
        onClick={() => onChange('ai')}
      >
        <span className="mt-ai-dot"></span>
        Talk instantly · AI
      </button>
      <span className={"mt-thumb" + (value === 'ai' ? " mt-thumb-r" : "")}></span>
    </div>
  );
}

// ─── Hero ──────────────────────────────────────────────────────
function Hero({ variant, mode, setMode, onJoin, headlineOverride }) {
  const isAI = variant === 'ai' || mode === 'ai';

  return (
    <section className="hero">
      <div className="hero-grain"></div>

      <div className="hero-inner">
        <div className="hero-left">
          <div className="eyebrow">
            <PulseDot color={isAI ? "oklch(0.78 0.14 75)" : undefined} />
            <span>
              {isAI ? "AI fallback · always on" : "Live voice · pay per minute"}
            </span>
          </div>

          <h1 className="h1">
            {isAI ? (
              <>
                No one online?<br/>
                <em>Talk to AI.</em> Instantly.
              </>
            ) : headlineOverride ? headlineOverride.h : (
              <>
                Talk to someone real.<br/>
                <em>Instantly.</em>
              </>
            )}
          </h1>

          <p className="sub">
            {isAI
              ? <>When no one's around, switch to AI instantly. Same voice-first feel, lower price, zero queue.</>
              : headlineOverride ? headlineOverride.sub
              : <>Real people. Real conversations.<br/>Talk 1:1 over voice. Pay per minute.</>}
          </p>

          <ModeToggle value={mode} onChange={setMode} />

          <div className="cta-row">
            <button className="btn btn-primary btn-lg" onClick={() => onJoin('user')}>
              Join waitlist
              <span className="btn-arrow">→</span>
            </button>
            <button className="btn btn-ghost btn-lg" onClick={() => onJoin('creator')}>
              Start earning
            </button>
          </div>

          <div className="trust-row">
            <span>Verified humans</span>
            <span className="trust-dot">·</span>
            <span>End-to-end private</span>
            <span className="trust-dot">·</span>
            <span>Pay only for what you use</span>
          </div>
        </div>

        <div className="hero-right">
          <PresenceOrb ai={isAI} />
        </div>
      </div>
    </section>
  );
}

// ─── Creators online row ───────────────────────────────────────
function CreatorsStrip({ onConnect }) {
  return (
    <section className="creators-strip">
      <div className="strip-head">
        <div className="strip-head-left">
          <Waveform bars={5} color="oklch(0.78 0.16 145)" height={11} />
          <span>128 people online right now</span>
        </div>
        <a className="strip-link" href="#all">See all 128 →</a>
      </div>
      <div className="creators-grid">
        {CREATORS.map(c => (
          <CreatorCard key={c.id} creator={c} onConnect={onConnect} />
        ))}
      </div>
    </section>
  );
}

// ─── How it works ──────────────────────────────────────────────
function HowItWorks() {
  const steps = [
    { n: '01', t: 'Find the right person',    d: 'Browse listeners, comics, chillers, mentors. Filter by vibe and rate.' },
    { n: '02', t: 'Start a voice call',      d: 'One tap connects. No queues, no friction.' },
    { n: '03', t: 'Pay per minute',          d: 'The clock starts when they pick up. Hang up when you want. No surprises.' },
  ];
  return (
    <section className="section" id="how">
      <div className="section-head">
        <div className="section-eyebrow">How it works</div>
        <h2 className="h2">Three steps. <em>That's it.</em></h2>
      </div>
      <div className="steps">
        {steps.map(s => (
          <div className="step" key={s.n}>
            <div className="step-n">{s.n}</div>
            <div className="step-t">{s.t}</div>
            <div className="step-d">{s.d}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─── Why people pay ────────────────────────────────────────────
function WhyPeoplePay() {
  const items = [
    { t: 'Feel heard',    d: 'Someone whose only job for the next seven minutes is you. No bots. No scripts.' },
    { t: 'Talk freely',   d: 'No followers. No likes. No record. Just a voice on the other end.' },
    { t: 'No judgment',   d: 'Stay anonymous. Speak your mind. Zero consequence.' },
    { t: 'No pressure',   d: 'Hang up any minute. Pay only for what you used. No commitment.' },
  ];
  return (
    <section className="section section-why" id="why">
      <div className="section-head">
        <div className="section-eyebrow">Why people pay</div>
        <h2 className="h2">Sometimes you just want <em>someone there</em>.</h2>
        <p className="earn-sub">Quiet luxury for your attention.</p>
      </div>
      <div className="why-grid">
        {items.map(it => (
          <div className="why-item" key={it.t}>
            <div className="why-bar"></div>
            <div className="why-t">{it.t}</div>
            <div className="why-d">{it.d}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─── Earn by talking (creator-facing) ──────────────────────────
function EarnByTalking({ onJoin }) {
  const items = [
    { t: 'Earn per minute',  d: 'Set your rate. Get paid the moment a call ends.' },
    { t: 'Flexible hours',   d: 'Toggle on when you feel like it. Toggle off when you don\'t.' },
    { t: 'Private or Public', d: "Start anonymous. Go public when you're ready." },
  ];
  return (
    <section className="section section-earn" id="earn">
      <div className="earn-inner">
        <div className="earn-left">
          <div className="section-eyebrow">Get paid to talk</div>
          <h2 className="h2">Earn by <em>talking</em>.</h2>
          <p className="earn-sub">
            Turn the conversations you'd have anyway into income. Set your rate.
            Pick your hours. Stay private.
          </p>
          <button className="btn btn-primary btn-lg" onClick={() => onJoin('creator')}>
            Start earning
            <span className="btn-arrow">→</span>
          </button>
        </div>
        <div className="earn-right">
          {items.map((it, i) => (
            <div className="earn-item" key={it.t}>
              <div className="earn-n">0{i+1}</div>
              <div>
                <div className="earn-t">{it.t}</div>
                <div className="earn-d">{it.d}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─── AI fallback section ───────────────────────────────────────
function AIFallback({ onJoin }) {
  return (
    <section className="section section-ai">
      <div className="ai-inner">
        <div className="ai-left">
          <div className="section-eyebrow ai-eyebrow">
            <span className="ai-eyebrow-dot"></span>
            AI fallback
          </div>
          <h2 className="h2">No one online? <em>Talk to AI.</em></h2>
          <p className="earn-sub">
            When no one's online, you can switch to AI instantly.
            Same instant connection, lower price, zero queue.
          </p>
          <div className="ai-pill-row">
            <div className="ai-pill"><span>₹4</span><span className="ai-pill-u">/min</span></div>
            <div className="ai-pill ai-pill-ghost">vs. ₹14–22/min with people</div>
          </div>
        </div>
        <div className="ai-right">
          <div className="ai-orb">
            <div className="ripple-stack">
              <span style={{ borderColor: 'oklch(0.84 0.14 75 / 0.35)' }}></span>
              <span style={{ borderColor: 'oklch(0.84 0.14 75 / 0.35)' }}></span>
            </div>
            <Waveform bars={11} color="oklch(0.84 0.14 75)" height={42} />
          </div>
        </div>
      </div>
    </section>
  );
}

// ─── Waitlist form ─────────────────────────────────────────────
function WaitlistInner({ initialRole, onSuccess, tsWidgetId, tsContainerRef }) {
  const [role, setRole] = React.useState(initialRole || 'user');
  const [contact, setContact] = React.useState('');
  const [touched, setTouched] = React.useState(false);
  const [status, setStatus] = React.useState('idle'); // idle | sending | done | error
  const [name, setName] = React.useState('');
  const [city, setCity] = React.useState('');
  const [gender, setGender] = React.useState('');
  const [extraStatus, setExtraStatus] = React.useState('idle'); // idle | sending | saved | error

  React.useEffect(() => { setRole(initialRole || 'user'); }, [initialRole]);

  const valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(contact) || /^[+\d][\d\s\-]{6,}$/.test(contact);

  const submit = async (e) => {
    e.preventDefault();
    setTouched(true);
    if (!valid) return;
    setStatus('sending');

    let turnstileToken = '';
    try {
      if (window.turnstile && tsWidgetId.current !== null) {
        turnstileToken = await window.turnstile.execute(tsWidgetId.current, { action: 'waitlist' });
      }
    } catch (_) {
      setStatus('error');
      return;
    }

    const normalizedContact = contact.trim();
    try {
      const res = await fetch('/api/waitlist', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ contact: normalizedContact, role, turnstileToken }),
      });
      if (!res.ok) {
        setStatus('error');
        return;
      }
    } catch (_) {
      setStatus('error');
      return;
    }

    setContact(normalizedContact);
    setStatus('done');
    onSuccess && onSuccess({ role, contact: normalizedContact });
  };

  const submitExtra = async (e) => {
    e.preventDefault();
    const cleanName = name.trim();
    const cleanCity = city.trim();
    if (!cleanName && !cleanCity && !gender) return;
    setExtraStatus('sending');

    let turnstileToken = '';
    try {
      if (window.turnstile && tsWidgetId.current !== null) {
        window.turnstile.reset(tsWidgetId.current);
        turnstileToken = await window.turnstile.execute(tsWidgetId.current, { action: 'waitlist-extra' });
      }
    } catch (_) {
      setExtraStatus('error');
      return;
    }

    try {
      const res = await fetch('/api/waitlist-extra', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ contact, name: cleanName, city: cleanCity, gender, turnstileToken }),
      });
      if (!res.ok) {
        setExtraStatus('error');
        return;
      }
    } catch (_) {
      setExtraStatus('error');
      return;
    }

    setExtraStatus('saved');
  };

  if (status === 'done') {
    return (
      <div className="waitlist-done">
        <div className="wd-check">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
            <path d="M5 13l4 4L19 7" />
          </svg>
        </div>
        <div className="wd-t">You're on the list.</div>
        <div className="wd-d">
          We'll reach out at <strong>{contact}</strong> when CallxCall opens to{' '}
          {role === 'creator' ? 'people earning' : 'people talking'}.
        </div>

        {extraStatus === 'saved' ? (
          <div className="wd-extra-thanks">
            Thanks{name ? `, ${name.split(' ')[0]}` : ''}. We'll prioritize you.
          </div>
        ) : (
          <form className="wd-extra" onSubmit={submitExtra}>
            <div className="wd-extra-eyebrow">Want priority access? <span className="wd-extra-opt">(optional)</span></div>
            <div className="wd-extra-row">
              <input
                className="wd-extra-input"
                placeholder="First name"
                value={name}
                onChange={e => setName(e.target.value)}
                maxLength={80}
                autoComplete="given-name"
              />
              <input
                className="wd-extra-input"
                placeholder="City"
                value={city}
                onChange={e => setCity(e.target.value)}
                maxLength={80}
                autoComplete="address-level2"
              />
            </div>
            <div className="wd-chips-row">
              <div className="wd-chips" role="radiogroup" aria-label="Gender">
                {['female', 'male', 'other'].map(g => (
                  <button
                    key={g}
                    type="button"
                    role="radio"
                    aria-checked={gender === g}
                    className={"wd-chip" + (gender === g ? ' wd-chip-active' : '')}
                    onClick={() => setGender(gender === g ? '' : g)}
                  >
                    {g.charAt(0).toUpperCase() + g.slice(1)}
                  </button>
                ))}
              </div>
              <button
                type="submit"
                className="wd-extra-submit"
                disabled={extraStatus === 'sending' || (!name.trim() && !city.trim() && !gender)}
              >
                {extraStatus === 'sending' ? <span className="spinner"></span> : <>Save <span style={{ marginLeft: 4 }}>→</span></>}
              </button>
            </div>
            {extraStatus === 'error' && (
              <div className="waitlist-err">Couldn't save. Try again in a moment.</div>
            )}
          </form>
        )}

      </div>
    );
  }

  return (
    <form className="waitlist" onSubmit={submit} noValidate>
      <div className="waitlist-eyebrow">I'm here to</div>
      <div className="role-toggle">
        <button
          type="button"
          className={"rt-btn" + (role === 'user' ? " rt-active" : "")}
          onClick={() => setRole('user')}
        >
          Talk
        </button>
        <button
          type="button"
          className={"rt-btn" + (role === 'creator' ? " rt-active" : "")}
          onClick={() => setRole('creator')}
        >
          Earn
        </button>
        <span className={"rt-thumb" + (role === 'creator' ? " rt-thumb-r" : "")}></span>
      </div>

      <label className="waitlist-label" htmlFor="contact">Phone or email</label>
      <div className={"waitlist-input-wrap" + (touched && !valid ? " err" : "")}>
        <input
          id="contact"
          className="waitlist-input"
          placeholder="you@somewhere.com  or  +91…"
          value={contact}
          onChange={e => {
            setContact(e.target.value);
            if (status === 'error') setStatus('idle');
          }}
          autoComplete="off"
        />
        <button
          type="submit"
          className="waitlist-submit"
          disabled={status === 'sending'}
        >
          {status === 'sending' ? (
            <span className="spinner"></span>
          ) : (
            <>Join <span style={{ marginLeft: 4 }}>→</span></>
          )}
        </button>
      </div>
      {touched && !valid && (
        <div className="waitlist-err">Enter a valid email or phone number.</div>
      )}
      {status === 'error' && (
        <div className="waitlist-err">Something went wrong. Try again in a moment.</div>
      )}
      <div className="waitlist-fine">
        We'll only contact you about CallxCall. No spam, ever.
      </div>
    </form>
  );
}

// Wrapper keeps the Turnstile container mounted across form ↔ done transitions
function Waitlist(props) {
  const tsContainerRef = React.useRef(null);
  const tsWidgetId = React.useRef(null);

  React.useEffect(() => {
    if (!window.turnstile || !tsContainerRef.current) return;
    if (tsWidgetId.current !== null) return;
    const siteKey = window.CALLXCALL_CONFIG && window.CALLXCALL_CONFIG.TURNSTILE_SITE_KEY;
    if (!siteKey) return;
    tsWidgetId.current = window.turnstile.render(tsContainerRef.current, {
      sitekey: siteKey,
      size: 'invisible',
      callback: () => {},
    });
  }, []);

  return (
    <div>
      <WaitlistInner {...props} tsContainerRef={tsContainerRef} tsWidgetId={tsWidgetId} />
      <div ref={tsContainerRef} style={{ display: 'none' }}></div>
    </div>
  );
}

// ─── Footer with waitlist ──────────────────────────────────────
function FooterCTA({ initialRole, formRef }) {
  const [submitted, setSubmitted] = React.useState(null);
  return (
    <section className="footer-cta" id="join" ref={formRef}>
      <div className="fc-inner">
        <div className="fc-left">
          <div className="section-eyebrow">Join the waitlist</div>
          <h2 className="h2">Be first when <em>the line opens</em>.</h2>
          <p className="earn-sub">
            Early users get priority access and lower rates. We're onboarding in small batches.
          </p>
        </div>
        <div className="fc-right">
          <Waitlist initialRole={initialRole} onSuccess={setSubmitted} />
        </div>
      </div>
      <div className="footer-bar">
        <div className="logo">
          <span className="logo-mark"><span></span><span></span><span></span></span>
          <span className="logo-text">CallxCall</span>
        </div>
        <div className="footer-fine">© 2026 · Voice-first, paid by the minute.</div>
      </div>
    </section>
  );
}

// ─── Connecting overlay ────────────────────────────────────────
function ConnectingOverlay({ creator, onCancel }) {
  const [phase, setPhase] = React.useState('dialing'); // dialing → ringing → connected
  const [seconds, setSeconds] = React.useState(0);

  React.useEffect(() => {
    if (!creator) return;
    setPhase('dialing');
    setSeconds(0);
    const t1 = setTimeout(() => setPhase('ringing'), 1100);
    const t2 = setTimeout(() => setPhase('connected'), 2700);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [creator]);

  React.useEffect(() => {
    if (phase !== 'connected') return;
    const id = setInterval(() => setSeconds(s => s + 1), 1000);
    return () => clearInterval(id);
  }, [phase]);

  if (!creator) return null;

  const cost = ((seconds / 60) * creator.rate).toFixed(2);
  const label = phase === 'dialing' ? 'Dialing…'
              : phase === 'ringing' ? 'Ringing…'
              : 'Connected';

  return (
    <div className="connecting-overlay" onClick={onCancel}>
      <div className="connecting-card" onClick={e => e.stopPropagation()}>
        <div className="connecting-orb-wrap">
          <div className="ripple-stack">
            <span></span><span></span><span></span>
          </div>
          <div
            className="connecting-orb"
            style={{
              background: `radial-gradient(circle at 35% 30%,
                oklch(0.78 0.14 ${creator.hue}) 0%,
                oklch(0.5 0.13 ${creator.hue}) 60%,
                oklch(0.28 0.07 ${creator.hue + 20}) 100%)`,
            }}
          ></div>
        </div>

        <div className="connecting-name">{creator.name}</div>
        <div className="connecting-tag">{creator.tag} · ₹{creator.rate}/min</div>

        <div className="connecting-status">
          {phase !== 'connected' && <span className="connecting-spinner"></span>}
          {phase === 'connected' && <Waveform bars={6} color="oklch(0.78 0.16 145)" height={14} />}
          <span>{label}</span>
        </div>

        {phase === 'connected' && (
          <div className="connecting-meter">
            <div className="cm-row">
              <span className="cm-label">Duration</span>
              <span className="cm-val">{Math.floor(seconds/60).toString().padStart(2,'0')}:{(seconds%60).toString().padStart(2,'0')}</span>
            </div>
            <div className="cm-row">
              <span className="cm-label">Cost so far</span>
              <span className="cm-val">₹{cost}</span>
            </div>
          </div>
        )}

        <button className="connecting-end" onClick={onCancel}>
          {phase === 'connected' ? 'End call' : 'Cancel'}
        </button>

        <div className="connecting-fine">
          {phase === 'connected'
            ? 'You can hang up any minute. You only pay for what you use.'
            : 'Connecting instantly. No queues.'}
        </div>
      </div>
    </div>
  );
}

window.Landing = {
  CREATORS, Nav, Hero, CreatorsStrip, HowItWorks, WhyPeoplePay,
  EarnByTalking, AIFallback, FooterCTA, ConnectingOverlay,
};
