/* global React, PAPERS, PaperTexture, Icon */
const { useState, useEffect } = React;

function SampleRequestPage({ navigate, addToCart }) {
  const [list, setList] = useState(() => {
    try { return JSON.parse(localStorage.getItem("ip_samples") || "[]"); }
    catch (e) { return []; }
  });
  const [submitted, setSubmitted] = useState(false);

  const removeOne = (id) => {
    const next = list.filter(x => x.id !== id);
    setList(next);
    localStorage.setItem("ip_samples", JSON.stringify(next));
  };

  // populate with recommended if empty
  const recommended = list.length === 0 ? (window._INDIE_CATALOG || window.PAPERS || []).slice(0, 6).map(p => ({
    id: p.id, brand: p.brand, name: p.name, gsm: p.gsm, finish: p.finish, tone: p.swatchTone
  })) : [];

  const displayed = list.length ? list : recommended;

  const handleSubmit = (e) => {
    e.preventDefault();
    setSubmitted(true);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  if (submitted) {
    return (
      <main className="fade-in">
        <div className="shell" style={{paddingBlock:"clamp(80px, 12vw, 160px)", textAlign:"center", maxWidth: 720}}>
          {/* Big stamp */}
          <div style={{
            display:"inline-block",
            border: "3px solid var(--terracotta)",
            color: "var(--terracotta)",
            padding: "10px 20px",
            fontFamily: "var(--font-mono)",
            fontSize: 14,
            letterSpacing: "0.24em",
            fontWeight: 700,
            transform: "rotate(-4deg)",
            marginBottom: 32,
          }}>SAMPLE KIT · CONFIRMED</div>

          <h1 style={{fontFamily:"var(--font-display)", fontSize: "clamp(40px, 7vw, 88px)", fontWeight: 300, letterSpacing:"-0.02em", lineHeight: 0.95, margin: 0}}>
            Sample kit on its <em style={{fontStyle:"italic", color:"var(--terracotta)"}}>way.</em>
          </h1>
          <p style={{fontSize: 18, color: "var(--ink-soft)", marginTop: 24, maxWidth: 520, marginInline:"auto"}}>
            Terima kasih. Tim kami akan menghubungi via WhatsApp dalam 1×24 jam untuk konfirmasi alamat. Free ongkir untuk Jabodetabek.
          </p>
          <div style={{marginTop: 40, display:"flex", gap: 10, justifyContent:"center", flexWrap:"wrap"}}>
            <button className="btn btn-primary btn-lg" onClick={() => navigate("/gallery")}>Back to gallery</button>
            <button className="btn btn-ghost btn-lg" onClick={() => { localStorage.removeItem("ip_samples"); setSubmitted(false); setList([]); }}>Send another</button>
          </div>

          {/* paper plane flight */}
          <svg viewBox="0 0 400 100" style={{width: "min(100%, 480px)", marginTop: 64}}>
            <path d="M5 80 Q 100 10 395 50" stroke="var(--terracotta)" strokeWidth="1.2" strokeDasharray="3 5" fill="none" />
            <g transform="translate(340 38) rotate(8)">
              <path d="M0 0 L42 14 L14 18 L9 30 L5 21 L-2 25 L0 0z" fill="var(--ink)" />
              <path d="M0 0 L14 18 L5 21 L-2 25 L0 0z" fill="var(--brand-yellow)" />
            </g>
          </svg>
        </div>
      </main>
    );
  }

  return (
    <main className="fade-in">
      {/* HERO */}
      <section className="sr-hero">
        <div className="shell">
          <span className="eyebrow eyebrow-ink">「 Free Sample Kit 」 ペーパー</span>
          <h1 style={{marginTop: 14}}>
            Get a<br/>
            sample <em>kit.</em><br/>
            Free.
          </h1>
          <p>Pilih sendiri 8 lembar kertas atau biarkan kami pilihkan favorit kami. Kami kirim — tinggal Anda timang, pegang, dan coba print sendiri di studio.</p>
        </div>
      </section>

      <div className="shell sr-shell">
        {/* LEFT — papers in kit */}
        <div>
          <div className="section-head" style={{marginBottom: 16}}>
            <h2 style={{fontSize: "clamp(24px, 3.4vw, 36px)"}}>
              {list.length > 0 ? <>Your kit · <em>{list.length} papers</em></> : <>Our <em>editor's</em> picks</>}
            </h2>
            <a className="more" onClick={() => navigate("/gallery")}>Add more →</a>
          </div>

          <div className="sr-papers">
            {displayed.map((p, i) => (
              <div key={p.id} className="sr-paper-row">
                <div className="sw" style={{position:"relative", overflow:"hidden"}}>
                  <PaperTexture tone={p.tone || "#F4ECD8"} grain="fiber" />
                </div>
                <div className="info">
                  <div className="b">{p.brand}</div>
                  <div className="n">{p.name}</div>
                  <div className="s">{p.gsm}gsm · {p.finish} · A4 sample</div>
                </div>
                {list.length > 0 ? (
                  <button className="x" onClick={() => removeOne(p.id)} title="Remove"><Icon.X /></button>
                ) : (
                  <span className="mono" style={{fontSize:11, color:"var(--ink-meta)"}}>recommended</span>
                )}
              </div>
            ))}
          </div>

          {list.length > 0 && list.length < 8 && (
            <p style={{marginTop: 14, color:"var(--ink-meta)", fontSize: 13.5}}>
              Anda bisa menambah hingga <strong style={{color:"var(--ink)"}}>{8 - list.length} kertas lagi</strong>. Atau kirim sekarang — kami akan lengkapi dengan rekomendasi kami.
            </p>
          )}
        </div>

        {/* RIGHT — form */}
        <form className="sr-form" onSubmit={handleSubmit}>
          <h3>Shipping details</h3>

          <div className="field">
            <label>Full name</label>
            <input type="text" placeholder="Nama lengkap" required />
          </div>

          <div className="row">
            <div className="field">
              <label>Email</label>
              <input type="email" placeholder="hello@studio.com" required />
            </div>
            <div className="field">
              <label>WhatsApp</label>
              <input type="text" placeholder="+62 81…" required style={{width:'100%', boxSizing:'border-box'}} />
            </div>
          </div>

          <div className="field">
            <label>Studio / Company (optional)</label>
            <input type="text" placeholder="Studio Tertier" />
          </div>

          <div className="field">
            <label>Shipping address</label>
            <textarea placeholder="Jl. Senopati No. 12, Jakarta Selatan, 12110" required></textarea>
          </div>

          <div className="field">
            <label>What are you working on? (optional)</label>
            <textarea placeholder="Identity untuk cafe? Packaging? Editorial? Cerita ke kami — kami bisa tambahkan rekomendasi kertas yang relevan." style={{minHeight: 64}}></textarea>
          </div>

          <button type="submit" className="btn btn-accent btn-lg btn-block">
            Send my sample kit
            <Icon.Arrow />
          </button>

          <div style={{fontSize: 11.5, color: "var(--ink-meta)", textAlign:"center", lineHeight: 1.5}}>
            Free shipping Jabodetabek · Rp 25.000 luar Jabodetabek<br/>
            We'll WhatsApp you within 1×24 hours.
          </div>
        </form>
      </div>

      {/* STEPS */}
      <div className="shell">
        <div className="sr-steps">
          {[
            { n: "01", h: "Pilih kertas", p: "Browse gallery, klik 'Request Sample' di kertas yang menarik. Atau pakai pilihan kami." },
            { n: "02", h: "Isi form ini", p: "Alamat, nomor WA, dan sedikit cerita tentang project Anda." },
            { n: "03", h: "Kami kirim", p: "Sample kit dalam amplop kraft — gratis untuk Jabodetabek." },
            { n: "04", h: "Order yang asli", p: "Setelah ketemu yang cocok, order pre-cut langsung dari gallery." },
          ].map(s => (
            <div key={s.n} className="sr-step">
              <div className="n">STEP {s.n}</div>
              <h4>{s.h}</h4>
              <p>{s.p}</p>
            </div>
          ))}
        </div>
      </div>
    </main>
  );
}

window.SampleRequestPage = SampleRequestPage;
