/* LandingSections.jsx - content below the scroll hero */

const MoreFeaturesSection = () => {
  const features = [
    { tag: 'Surveys', title: 'Run surveys against 10,000 personas in 90 seconds', body: 'Likert, NPS, MaxDiff, Van Westendorp - all native templates. Results stratified by any persona attribute.' },
    { tag: 'Concept tests', title: 'Drop in a mockup. Get reactions before lunch.', body: 'Image, video, or copy. Personas react in their own voice; sentiment + open-ended feedback are auto-coded.' },
    { tag: 'Branching what-ifs', title: 'Re-run the same simulation, change one variable', body: 'Cut income by 30%. Switch geography. Add a competitor. Compare branches side-by-side.' },
    { tag: 'Cross-agent influence', title: 'Personas talk to each other, not just to you', body: 'Model word-of-mouth, social proof, and platform-specific posting behavior across Reddit, IG, X, WhatsApp, TikTok.' },
    { tag: 'Cohort dashboards', title: 'Slice by belief, not just by demographic', body: 'Group personas by eco-concern, price sensitivity, brand loyalty - any latent attribute, not just age and zip.' },
    { tag: 'Replay & export', title: 'Every decision is auditable, every transcript is yours', body: 'Export to CSV, Notion, Figma, or your data warehouse. Full provenance for every persona belief.' },
  ];

  return (
    <section style={{ padding: '120px 32px 96px', maxWidth: 1280, margin: '0 auto' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 64, marginBottom: 64, alignItems: 'end' }}>
        <div>
          <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 700, color: 'var(--accent-2)', marginBottom: 14 }}>
            And there's much more
          </div>
          <h2 style={{
            fontFamily: 'var(--font-display)', fontWeight: 400,
            fontSize: 'clamp(40px, 4.5vw, 60px)', lineHeight: 1.02,
            letterSpacing: '-0.025em', color: 'var(--fg-1)', margin: 0,
          }}>
            And there's <em style={{ color: 'var(--accent)', fontStyle: 'italic' }}>so much more</em> Lokara can do.
          </h2>
        </div>
        <p style={{ fontSize: 16, lineHeight: 1.6, color: 'var(--fg-2)', margin: 0, maxWidth: 480, justifySelf: 'end' }}>
          The build / decide / talk loop is the spine. Everything else - surveys, concept tests, what-if branching, cross-agent influence - sits on top of it.
        </p>
      </div>

      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)',
        gap: 1, background: 'var(--border-1)',
        border: '1px solid var(--border-1)', borderRadius: 16, overflow: 'hidden',
      }}>
        {features.map((f, i) => (
          <div key={i} style={{
            padding: '32px 28px',
            background: 'var(--bg-elevated)',
            display: 'flex', flexDirection: 'column', gap: 14, minHeight: 240,
          }}>
            <span style={{
              alignSelf: 'flex-start',
              fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 700,
              letterSpacing: '0.1em', textTransform: 'uppercase',
              color: 'var(--accent-deep)',
              padding: '4px 10px', borderRadius: 999,
              background: 'var(--accent-soft-bg)',
            }}>{f.tag}</span>
            <h3 style={{
              fontSize: 19, fontWeight: 600, lineHeight: 1.25,
              color: 'var(--fg-1)', margin: 0, letterSpacing: '-0.01em',
            }}>{f.title}</h3>
            <p style={{ fontSize: 14, lineHeight: 1.55, color: 'var(--fg-2)', margin: 0 }}>{f.body}</p>
            <div style={{ marginTop: 'auto', fontSize: 12, color: 'var(--accent)', fontWeight: 600 }}>
              Learn more →
            </div>
          </div>
        ))}
      </div>

      <div style={{ textAlign: 'center', marginTop: 56 }}>
        <a href="#" style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          fontSize: 14, fontWeight: 600, color: 'var(--fg-1)',
          textDecoration: 'none',
          padding: '12px 22px', borderRadius: 999,
          border: '1px solid var(--border-2)',
          background: 'var(--bg-elevated)',
        }}>
          See every capability <span style={{ color: 'var(--accent)' }}>→</span>
        </a>
      </div>
    </section>
  );
};

/* Live "simulations running" counter.
   Source of truth: Postgres function public.simulations_running() — same
   value for everyone, changes every 7 minutes. The JS fallback below uses
   the same 7-minute bucketing so the cadence is preserved if the DB is
   unreachable or the function isn't created yet. Range: [110, 844]. */
const SIMS_BUCKET_SECONDS = 420; // 7 min
const SIMS_MIN = 110;
const SIMS_RANGE = 735;          // 110..844
const computeLiveSimsFallback = (now = Date.now()) => {
  const bucket = Math.floor((now / 1000) / SIMS_BUCKET_SECONDS);
  const h = (Math.imul(bucket, 2654435761) >>> 0); // unsigned 32-bit hash
  return SIMS_MIN + (h % SIMS_RANGE);
};

const useLiveSims = () => {
  const [n, setN] = React.useState(() => computeLiveSimsFallback());

  React.useEffect(() => {
    let cancelled = false;
    const tick = async () => {
      const fetcher = window.lokaraFetchLiveSims;
      const v = fetcher ? await fetcher() : null;
      if (cancelled) return;
      setN(typeof v === 'number' ? v : computeLiveSimsFallback());
    };
    tick();
    // Re-fetch every 7 minutes. setTimeout chain (not setInterval) so each
    // tick aligns with the wall-clock bucket boundary roughly.
    const id = setInterval(tick, SIMS_BUCKET_SECONDS * 1000);
    return () => { cancelled = true; clearInterval(id); };
  }, []);

  return n;
};

window.useLiveSims = useLiveSims;

/* Numbers band */
const NumbersBand = () => {
  const liveSims = useLiveSims();
  const stats = [
    { val: '< 90s', lbl: 'Avg time from prompt to first result' },
    { val: '10,000', lbl: 'Personas per simulation, max' },
    { val: liveSims.toLocaleString(), lbl: 'Simulations running right now', live: true },
    { val: '94%', lbl: 'Concept tests that match real-world results' },
  ];
  return (
    <section style={{ padding: '96px 32px', maxWidth: 1280, margin: '0 auto' }}>
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
        background: 'var(--accent)', borderRadius: 20,
        overflow: 'hidden',
        boxShadow: 'var(--shadow-lg)',
      }}>
        {stats.map((s, i) => (
          <div key={i} style={{
            padding: '36px 28px',
            borderRight: i < stats.length - 1 ? '1px solid rgba(255,255,255,0.16)' : 'none',
            position: 'relative',
          }}>
            {s.live && (
              <span aria-hidden="true" style={{
                position: 'absolute', top: 18, right: 18,
                display: 'inline-flex', alignItems: 'center', gap: 6,
                fontSize: 10, fontWeight: 700, letterSpacing: '0.12em',
                textTransform: 'uppercase', color: 'rgba(255,255,255,0.78)',
              }}>
                <span style={{
                  width: 7, height: 7, borderRadius: '50%',
                  background: '#7CFFB7',
                  boxShadow: '0 0 0 0 rgba(124,255,183,0.7)',
                  animation: 'lokaraLivePulse 1.6s ease-out infinite',
                }} />
                LIVE
              </span>
            )}
            <div style={{
              fontFamily: 'var(--font-display)', fontWeight: 400,
              fontSize: 'clamp(36px, 4vw, 56px)', lineHeight: 1,
              letterSpacing: '-0.025em',
              color: '#fff',
              fontVariantNumeric: 'tabular-nums',
              marginBottom: 12,
            }}>{s.val}</div>
            <div style={{ fontSize: 13, lineHeight: 1.5, color: 'rgba(255,255,255,0.82)' }}>{s.lbl}</div>
          </div>
        ))}
      </div>
    </section>
  );
};

/* Final CTA */
const FinalCTA = () => {
  const [email, setEmail] = React.useState('');
  const [interest, setInterest] = React.useState('');
  const [status, setStatus] = React.useState('idle'); // idle | submitting | success | error
  const [message, setMessage] = React.useState('');

  const onSubmit = async (e) => {
    e.preventDefault();
    if (status === 'submitting') return;
    const trimmed = email.trim();
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(trimmed)) {
      setStatus('error');
      setMessage('Please enter a valid email.');
      return;
    }
    setStatus('submitting');
    setMessage('');

    const submit = window.lokaraSubmitSignup || (() => Promise.resolve({}));
    const track  = window.lokaraTrack        || (() => {});

    const res = await submit({ email: trimmed, interest });
    const err = res && res.error;
    if (err) {
      const isDup = err.code === '23505' || /duplicate/i.test(err.message || '');
      if (isDup) {
        setStatus('success');
        setMessage("You're already on the list - see you soon.");
        track('signup_duplicate', { interest });
        return;
      }
      setStatus('error');
      setMessage(err.message || 'Something went wrong. Try again?');
      return;
    }
    setStatus('success');
    setMessage("Thanks - we'll be in touch within 24 hours.");
    track('signup_submitted', { interest_present: !!interest });
  };

  return (
    <section id="get-demo" style={{ padding: '64px 32px 120px', maxWidth: 1280, margin: '0 auto' }}>
      <div style={{
        background: 'var(--bg-sunken)',
        border: '1px solid var(--border-1)',
        borderRadius: 20,
        padding: 'clamp(40px, 6vw, 72px)',
        display: 'grid', gridTemplateColumns: '1.4fr 1fr',
        gap: 48, alignItems: 'center',
      }}>
        <div>
          <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 700, color: 'var(--accent-2)', marginBottom: 16 }}>
            Free for design partners
          </div>
          <h2 style={{
            fontFamily: 'var(--font-display)', fontWeight: 400,
            fontSize: 'clamp(36px, 4vw, 56px)', lineHeight: 1.02,
            letterSpacing: '-0.025em', color: 'var(--fg-1)', margin: '0 0 16px',
          }}>
            Stop guessing what your customers want.<br/>
            <em style={{ color: 'var(--accent)', fontStyle: 'italic' }}>Ask them.</em>
          </h2>
          <p style={{ fontSize: 16, lineHeight: 1.55, color: 'var(--fg-2)', margin: 0, maxWidth: 480 }}>
            See how Lokara fits your team. 30 minutes, your concept, our personas - you'll leave with a working simulation.
          </p>
        </div>
        <form onSubmit={onSubmit} style={{
          display: 'flex', flexDirection: 'column', gap: 10,
          background: 'var(--bg-elevated)', borderRadius: 14,
          padding: 22, border: '1px solid var(--border-1)',
          boxShadow: 'var(--shadow-md)',
        }}>
          <input
            type="email"
            required
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="Work email"
            disabled={status === 'submitting'}
            style={{
              padding: '12px 14px', fontSize: 14, fontFamily: 'inherit',
              border: '1px solid var(--border-2)', borderRadius: 8,
              background: 'var(--bg-elevated)', color: 'var(--fg-1)', outline: 'none',
            }}
          />
          <input
            type="text"
            value={interest}
            onChange={(e) => setInterest(e.target.value)}
            placeholder="What you'd test first"
            disabled={status === 'submitting'}
            style={{
              padding: '12px 14px', fontSize: 14, fontFamily: 'inherit',
              border: '1px solid var(--border-2)', borderRadius: 8,
              background: 'var(--bg-elevated)', color: 'var(--fg-1)', outline: 'none',
            }}
          />
          <button
            type="submit"
            disabled={status === 'submitting' || status === 'success'}
            style={{
              padding: '13px 20px', borderRadius: 8, border: 'none',
              background: status === 'success' ? 'var(--accent)' : 'var(--accent-2)',
              color: '#fff',
              fontSize: 14, fontWeight: 600,
              cursor: status === 'submitting' ? 'progress' : status === 'success' ? 'default' : 'pointer',
              fontFamily: 'inherit', marginTop: 4,
              opacity: status === 'submitting' ? 0.75 : 1,
              transition: 'background 200ms ease, opacity 200ms ease',
            }}
          >
            {status === 'submitting' ? 'Sending…'
              : status === 'success' ? 'On the list ✓'
              : 'Request a demo →'}
          </button>
          {message && (
            <div role="status" style={{
              fontSize: 12,
              color: status === 'error' ? 'var(--danger, #B84438)' : 'var(--accent)',
              textAlign: 'center', marginTop: 4,
            }}>{message}</div>
          )}
          <div style={{ fontSize: 11, color: 'var(--fg-3)', textAlign: 'center', marginTop: 6 }}>
            Reply within 24 hours · No credit card · No sales call
          </div>
        </form>
      </div>
    </section>
  );
};

const Footer = () => (
  <footer style={{
    borderTop: '1px solid var(--border-1)',
    padding: '36px 32px',
    background: 'var(--bg)',
  }}>
    <div style={{ maxWidth: 1280, margin: '0 auto', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 24, flexWrap: 'wrap' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 }}>
        <img src="logo.png" alt="" style={{ height: 32, flexShrink: 0 }} />
        <span style={{
          fontFamily: '"Manrope", var(--font-sans)',
          fontSize: 22,
          fontWeight: 800,
          color: 'var(--fg-1)',
          letterSpacing: '-0.02em',
          whiteSpace: 'nowrap',
          lineHeight: 1,
        }}>Lokara</span>
        <span style={{ fontSize: 12, color: 'var(--fg-3)', marginLeft: 12 }}>Synthetic consumer research, made tangible.</span>
      </div>
      <div style={{ display: 'flex', gap: 22, fontSize: 12, color: 'var(--fg-3)' }}>
        <a href="#" style={{ color: 'inherit', textDecoration: 'none' }}>Pricing</a>
        <a href="#" style={{ color: 'inherit', textDecoration: 'none' }}>Privacy</a>
        <a href="#" style={{ color: 'inherit', textDecoration: 'none' }}>Terms</a>
        <a href="#" style={{ color: 'inherit', textDecoration: 'none' }}>Status</a>
        <span>© 2026 Lokara · A product of WeaveStudio AI Pvt Ltd</span>
      </div>
    </div>
  </footer>
);

const ThemeToggle = ({ theme, onToggle }) => {
  const isDark = theme === 'dark';
  const faceBase = {
    position: 'absolute', inset: 0,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    fontSize: 16, lineHeight: 1,
    color: 'var(--accent)',
    backfaceVisibility: 'hidden',
    WebkitBackfaceVisibility: 'hidden',
  };
  return (
    <button
      onClick={onToggle}
      role="switch"
      aria-checked={isDark}
      aria-label={isDark ? 'Switch to light mode' : 'Switch to dark mode'}
      title={isDark ? 'Switch to light' : 'Switch to dark'}
      style={{
        width: 36, height: 36,
        borderRadius: 10,
        border: '1px solid var(--border-2)',
        background: 'var(--bg-elevated)',
        cursor: 'pointer',
        padding: 0,
        position: 'relative',
        perspective: '500px',
        flexShrink: 0,
        transition: 'background 240ms ease, border-color 240ms ease',
        WebkitTapHighlightColor: 'transparent',
      }}
    >
      <span aria-hidden="true" style={{
        position: 'absolute', inset: 0,
        transformStyle: 'preserve-3d',
        WebkitTransformStyle: 'preserve-3d',
        transform: isDark ? 'rotateY(180deg)' : 'rotateY(0deg)',
        transition: 'transform 480ms cubic-bezier(0.34, 1.2, 0.5, 1)',
      }}>
        <span style={faceBase}>☀</span>
        <span style={{ ...faceBase, transform: 'rotateY(180deg)' }}>☾</span>
      </span>
    </button>
  );
};

const Nav = ({ theme, onToggleTheme }) => (
  <nav data-marketing-nav style={{
    position: 'sticky', top: 0, zIndex: 50,
    height: 64, padding: '0 32px',
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    backdropFilter: 'saturate(180%) blur(18px)',
    WebkitBackdropFilter: 'saturate(180%) blur(18px)',
  }}>
    <a href="#" style={{
      display: 'flex', alignItems: 'center', gap: 12,
      textDecoration: 'none', flexShrink: 0,
    }}>
      <img src="logo.png" alt="" style={{ height: 40, flexShrink: 0 }} />
      <span style={{
        fontFamily: '"Manrope", var(--font-sans)',
        fontSize: 27,
        fontWeight: 800,
        color: 'var(--fg-1)',
        letterSpacing: '-0.02em',
        whiteSpace: 'nowrap',
        lineHeight: 1,
      }}>Lokara</span>
    </a>
    <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
      <ThemeToggle theme={theme} onToggle={onToggleTheme} />
      <a href="#" style={{
        fontSize: 13, fontWeight: 500, color: 'var(--fg-2)',
        textDecoration: 'none', padding: '8px 12px',
      }}>Sign in</a>
      <button
        onClick={() => {
          if (window.lokaraTrack) window.lokaraTrack('cta_click', { location: 'nav' });
          const target = document.getElementById('get-demo');
          if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }}
        style={{
          padding: '8px 14px', borderRadius: 6, border: 'none',
          background: 'var(--accent)', color: '#fff',
          fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
        }}
      >Request a demo</button>
    </div>
  </nav>
);

window.MoreFeaturesSection = MoreFeaturesSection;
window.NumbersBand = NumbersBand;
window.FinalCTA = FinalCTA;
window.Footer = Footer;
window.Nav = Nav;
