// landing.jsx — Landingpage + login/opret konto
const { useState: useStateL } = React;

function Landing({ onAuthed }) {
  const [auth, setAuth] = useStateL(null); // null | 'login' | 'signup'

  return (
    <div className="scroll" style={{ height: '100%', background:
      'radial-gradient(1200px 600px at 80% -10%, var(--accent-tint), transparent 60%), radial-gradient(900px 500px at 0% 110%, var(--sage-tint), transparent 55%), var(--bg)' }}>
      {/* top bar */}
      <header className="row lp-header" style={{ padding: '22px 40px', maxWidth: 1180, margin: '0 auto', justifyContent: 'space-between' }}>
        <Logo size={32} />
        <div className="row gap-3">
          <button className="btn btn-ghost" onClick={() => setAuth('login')}>Log ind</button>
          <button className="btn btn-primary" onClick={() => setAuth('signup')}>Kom i gang</button>
        </div>
      </header>

      {/* hero */}
      <section className="lp-hero" style={{ maxWidth: 1180, margin: '0 auto', padding: '40px 40px 30px', display: 'grid', gridTemplateColumns: '1.05fr 1fr', gap: 56, alignItems: 'center' }}>
        <div className="anim-up">
          <div className="chip" style={{ background: 'var(--surface)', marginBottom: 22 }}>
            <span className="dot gc-1"></span> Lavet til familiefester
          </div>
          <h1 className="lp-hero-title" style={{ fontSize: 56, lineHeight: 1.04, letterSpacing: '-.03em', marginBottom: 20 }}>
            Bordplanen, der <span style={{ color: 'var(--accent)' }}>bare</span> falder på plads.
          </h1>
          <p style={{ fontSize: 20, lineHeight: 1.55, color: 'var(--ink-soft)', maxWidth: 480, marginBottom: 30 }}>
            Saml gæsterne, træk dem ned til bordene og se det hele gå op. Planiq gør det nemt at lave bordplaner til barnedåb, konfirmation, bryllup og fødselsdag — helt uden besvær.
          </p>
          <div className="row gap-3" style={{ flexWrap: 'wrap' }}>
            <button className="btn btn-primary btn-lg" onClick={() => setAuth('signup')}>
              Kom i gang <Icon name="chevR" size={20} />
            </button>
            <button className="btn btn-lg" onClick={() => setAuth('login')}>Jeg har en konto</button>
          </div>
          <div className="row gap-4" style={{ marginTop: 30, color: 'var(--ink-faint)', fontSize: 15, fontWeight: 700 }}>
            <span className="row gap-2"><Icon name="check" size={18} color="var(--sage-deep)" /> Gemmer automatisk</span>
            <span className="row gap-2"><Icon name="check" size={18} color="var(--sage-deep)" /> Virker på iPad</span>
            <span className="row gap-2"><Icon name="check" size={18} color="var(--sage-deep)" /> Print &amp; del</span>
          </div>
        </div>

        {/* hero illustration: a little table-plan preview */}
        <div className="anim-pop lp-hero-art" style={{ animationDelay: '.08s' }}>
          <HeroPreview />
        </div>
      </section>

      {/* feature trio */}
      <section className="lp-features" style={{ maxWidth: 1180, margin: '0 auto', padding: '24px 40px 70px', display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 22 }}>
        {[
          { ic: 'users', t: "Saml gæsterne", b: "Tast navne på et øjeblik, grupper familie og venner, og hold styr på +1 og børn." },
          { ic: 'table', t: "Træk til bordene", b: "Runde borde, langborde, firkanter og hestesko. Træk en gæst ned på en plads — så enkelt er det." },
          { ic: 'heart', t: "Hold festen glad", b: "Markér hvem der skal — eller ikke skal — sidde sammen, og lad Planiq foreslå en plan." },
        ].map((f, i) => (
          <div key={i} className="card anim-up" style={{ padding: 26, animationDelay: `${.12 + i * .06}s` }}>
            <div style={{ width: 52, height: 52, borderRadius: 16, background: 'var(--accent-tint)', display: 'grid', placeItems: 'center', marginBottom: 16 }}>
              <Icon name={f.ic} size={26} color="var(--accent-deep)" sw={1.8} />
            </div>
            <h3 style={{ fontSize: 21, marginBottom: 8 }}>{f.t}</h3>
            <p className="muted" style={{ fontSize: 16, lineHeight: 1.5 }}>{f.b}</p>
          </div>
        ))}
      </section>

      {auth && <AuthModal mode={auth} setMode={setAuth} onClose={() => setAuth(null)} onAuthed={onAuthed} />}
    </div>
  );
}

function HeroPreview() {
  // decorative mini table plan
  const seats = (cx, cy, r, n, filled) => Array.from({ length: n }, (_, i) => {
    const a = (i / n) * Math.PI * 2 - Math.PI / 2;
    return <circle key={i} cx={cx + Math.cos(a) * r} cy={cy + Math.sin(a) * r} r="13"
      fill={i < filled ? `var(--grp-${(i % 5) + 1})` : 'var(--surface)'} stroke="var(--line-2)" strokeWidth="1.5" />;
  });
  return (
    <div className="card" style={{ padding: 18, background: 'var(--bg-2)', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0, backgroundImage: 'radial-gradient(var(--line-2) 1.2px, transparent 1.2px)', backgroundSize: '22px 22px', opacity: .5 }}></div>
      <svg viewBox="0 0 420 340" style={{ width: '100%', display: 'block', position: 'relative' }}>
        {/* round table */}
        <circle cx="120" cy="115" r="48" fill="var(--surface)" stroke="var(--line-2)" strokeWidth="2" />
        {seats(120, 115, 70, 6, 4)}
        {/* long table */}
        <rect x="225" y="80" width="150" height="56" rx="16" fill="var(--surface)" stroke="var(--line-2)" strokeWidth="2" />
        {[0,1,2,3].map(i => <circle key={i} cx={250 + i*33} cy="62" r="12" fill={`var(--grp-${(i%5)+1})`} stroke="var(--line-2)" strokeWidth="1.5" />)}
        {[0,1,2,3].map(i => <circle key={'b'+i} cx={250 + i*33} cy="154" r="12" fill={i<2?`var(--grp-${(i%5)+1})`:'var(--surface)'} stroke="var(--line-2)" strokeWidth="1.5" />)}
        {/* second round */}
        <circle cx="270" cy="250" r="44" fill="var(--surface)" stroke="var(--line-2)" strokeWidth="2" />
        {seats(270, 250, 65, 6, 3)}
        {/* floating dragged guest */}
        <g style={{ filter: 'drop-shadow(0 8px 14px rgba(78,60,40,.28))' }}>
          <circle cx="120" cy="250" r="18" fill="var(--accent)" stroke="#fff" strokeWidth="2.5" />
          <text x="120" y="256" textAnchor="middle" fontSize="14" fontWeight="800" fill="#fff" fontFamily="Fredoka">ML</text>
        </g>
        <text x="120" y="305" textAnchor="middle" fontSize="13" fontWeight="700" fill="var(--ink-soft)" fontFamily="Nunito">Træk til bord →</text>
      </svg>
      <div className="row" style={{ position: 'absolute', top: 26, right: 26, gap: 8 }}>
        <div className="chip" style={{ background: 'var(--surface)' }}><span className="dot gc-2"></span> 18 placeret</div>
      </div>
    </div>
  );
}

function AuthModal({ mode, setMode, onClose, onAuthed }) {
  const isSignup = mode === 'signup';
  const [name, setName] = useStateL('');
  const [email, setEmail] = useStateL('');
  const [pw, setPw] = useStateL('');
  const [err, setErr] = useStateL('');
  const [busy, setBusy] = useStateL(false);
  // Firebase kræver mindst 6 tegn ved oprettelse.
  const valid = email.includes('@') && pw.length >= (isSignup ? 6 : 4) && (!isSignup || name.trim());

  async function submit() {
    const fb = window.PlaniqFirebase;
    if (!fb) { setErr('Forbindelsen til serveren er ikke klar endnu. Prøv igen.'); return; }
    setErr('');
    setBusy(true);
    try {
      const user = isSignup
        ? await fb.signup(name.trim(), email.trim(), pw)
        : await fb.login(email.trim(), pw);
      // app.jsx lytter selv på auth-tilstanden; vi sender det viste navn med videre.
      onAuthed(user.displayName || name.trim() || user.email);
    } catch (e) {
      setErr(fb.danskFejl(e.code));
      setBusy(false);
    }
  }

  return (
    <Modal onClose={onClose} maxWidth={420}>
      <div className="center" style={{ marginBottom: 18 }}><Logo size={30} /></div>
      <h2 style={{ textAlign: 'center', marginBottom: 4 }}>{isSignup ? "Opret din konto" : "Velkommen tilbage"}</h2>
      <p className="muted center" style={{ fontSize: 15, marginBottom: 24 }}>
        {isSignup ? "Det tager under et minut." : "Log ind og fortsæt din plan."}
      </p>
      <div className="col gap-3" style={{ marginBottom: 22 }}>
        {isSignup && (
          <div className="field"><label>Dit navn</label>
            <input className="input" placeholder="Fornavn Efternavn" value={name} onChange={e => setName(e.target.value)} /></div>
        )}
        <div className="field"><label>E-mail</label>
          <input className="input" type="email" placeholder="dig@eksempel.dk" value={email} onChange={e => setEmail(e.target.value)} /></div>
        <div className="field"><label>Adgangskode</label>
          <input className="input" type="password" placeholder="••••••••" value={pw}
            onChange={e => setPw(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter' && valid && !busy) submit(); }} />
          {isSignup && <span className="muted" style={{ fontSize: 13 }}>Mindst 6 tegn.</span>}
        </div>
      </div>
      {err && <p style={{ color: 'var(--danger, #c0392b)', fontSize: 14, marginBottom: 14, textAlign: 'center' }}>{err}</p>}
      <button className="btn btn-primary btn-lg" style={{ width: '100%' }} disabled={!valid || busy}
        onClick={submit}>
        {busy ? "Vent…" : isSignup ? "Opret konto" : "Log ind"}
      </button>
      <p className="center muted" style={{ fontSize: 15, marginTop: 18 }}>
        {isSignup ? "Har du allerede en konto?" : "Ny her?"}&nbsp;
        <button className="btn-ghost" style={{ color: 'var(--accent-deep)', fontWeight: 800, padding: 0, minHeight: 0 }}
          onClick={() => setMode(isSignup ? 'login' : 'signup')}>
          {isSignup ? "Log ind" : "Opret en konto"}
        </button>
      </p>
    </Modal>
  );
}

Object.assign(window, { Landing });
