/* @jsx React.createElement */
// Domain Picker for INDIE Labs.
// Markup: ~12.5% above Qwords base (mid of 10-15%). Prices = indicative.
// Edit QWORDS_BASE freely; markup logic stays the same.

const { useState: useStateD, useMemo: useMemoD } = React;

// Indicative Qwords reseller pricing (IDR / year, before PPN).
// Update these when Qwords changes — markup auto-recalculates.
const QWORDS_BASE = {
  ".com":    165000,
  ".id":     275000,
  ".co.id":  395000,
  ".my.id":   55000,
  ".web.id":  50000,
  ".xyz":    250000,
};

const TLD_META = [
  { ext: ".com",    tag: "Standard",         note: "Pilih kalau brand-mu mau main di pasar global." },
  { ext: ".id",     tag: "Premium ID",       note: "Identitas lokal yang dipercaya. Wajib KTP." },
  { ext: ".co.id",  tag: "Korporat",         note: "Buat brand dengan NPWP + dokumen perusahaan." },
  { ext: ".my.id",  tag: "Personal / UKM",   note: "Ringan di kantong, KTP cukup." },
  { ext: ".web.id", tag: "Affordable",       note: "Murah meriah buat micro-site & landing." },
  { ext: ".xyz",    tag: "Startup vibe",     note: "Anak-anak founder & tech project." },
];

const DOMAIN_MARKUP = 0.125; // 12.5%
const PPN = 0.11;

function markupPrice(base) {
  // Round up to nearest 1000 for clean display
  const raw = base * (1 + DOMAIN_MARKUP);
  return Math.ceil(raw / 1000) * 1000;
}

function fmtIDR(n) {
  return "Rp " + n.toLocaleString("id-ID");
}

// Bad-name heuristic: domains < 3 chars or banned words → "Taken"
const TAKEN = new Set(["google", "facebook", "apple", "amazon", "microsoft", "youtube", "tokopedia", "shopee", "gojek", "bca"]);

function checkAvailability(name) {
  const n = name.toLowerCase().trim();
  if (!n) return "empty";
  if (n.length < 3) return "tooshort";
  if (TAKEN.has(n)) return "taken";
  if (/[^a-z0-9-]/.test(n)) return "invalid";
  return "available";
}

function DomainPicker() {
  const [q, setQ] = useStateD("");
  const [cart, setCart] = useStateD([]); // [{ ext, year }]
  const status = useMemoD(() => checkAvailability(q), [q]);
  const clean = q.toLowerCase().replace(/[^a-z0-9-]/g, "").trim();

  const toggle = (ext) => {
    if (cart.find((c) => c.ext === ext)) {
      setCart(cart.filter((c) => c.ext !== ext));
    } else {
      setCart([...cart, { ext, year: 1 }]);
    }
  };

  const setYear = (ext, year) => {
    setCart(cart.map((c) => c.ext === ext ? { ...c, year } : c));
  };

  const total = cart.reduce((sum, c) => sum + markupPrice(QWORDS_BASE[c.ext]) * c.year, 0);

  const order = () => {
    if (!cart.length || !clean) return;
    const lines = cart.map((c) => {
      const price = markupPrice(QWORDS_BASE[c.ext]) * c.year;
      return `• ${clean}${c.ext} · ${c.year} thn · ${fmtIDR(price)}`;
    });
    const msg = [
      `Halo INDIE Labs, saya mau pesan domain:`,
      ``,
      ...lines,
      ``,
      `Subtotal: ${fmtIDR(total)}`,
      `PPN 11%: ${fmtIDR(Math.round(total * PPN))}`,
      `*Total: ${fmtIDR(Math.round(total * (1 + PPN)))}*`,
      ``,
      `Mohon dibantu cek availability + langkah berikutnya. Terima kasih!`,
    ].join("\n");
    window.open(WA_LINK(msg), "_blank");
  };

  return (
    <section className="section" id="domains">
      <div className="container">
        <SectionHead
          eye="// domain · one-pintu"
          title={<>Sekalian punya<br/>alamat sendiri.</>}
          desc="Brand baru selalu butuh satu hal sebelum bisa hadir: nama yang bisa diketik orang. Cek ketersediaan domain di sini — kami yang urusin pendaftaran, perpanjangan, dan setup ke web kamu."
        />

        <div className="card" style={{
          marginTop: 56,
          background: "var(--labs-surface)",
          borderColor: "var(--labs-line-2)",
          padding: 32,
        }}>
          <div style={{ display: "flex", gap: 10, alignItems: "stretch", flexWrap: "wrap" }}>
            <div style={{ position: "relative", flex: "1 1 320px" }}>
              <input
                className="field"
                value={q}
                onChange={(e) => setQ(e.target.value)}
                placeholder="brandkamu"
                style={{ fontSize: 18, padding: "16px 14px", fontFamily: "var(--font-mono)", letterSpacing: "-0.01em" }}
              />
              {clean && (
                <span style={{
                  position: "absolute", right: 14, top: "50%", transform: "translateY(-50%)",
                  fontFamily: "var(--font-mono)", fontSize: 14, color: "var(--labs-fg-3)",
                  pointerEvents: "none",
                }}>
                  .com .id .co.id …
                </span>
              )}
            </div>
            <button onClick={() => setQ(q.trim())} className="btn btn-primary" style={{ padding: "0 22px" }}>
              Cek ketersediaan →
            </button>
          </div>

          {status === "tooshort" && q.length > 0 && (
            <div style={{ marginTop: 14, fontSize: 13, color: "var(--labs-fg-3)" }}>
              Min. 3 karakter ya.
            </div>
          )}
          {status === "invalid" && (
            <div style={{ marginTop: 14, fontSize: 13, color: "#ff9a8a" }}>
              Cuma boleh huruf, angka, dan tanda <code>-</code>.
            </div>
          )}

          {status === "available" && (
            <>
              <div className="rule" style={{ margin: "24px 0" }} />
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 14, flexWrap: "wrap", gap: 8 }}>
                <div className="eyebrow-dim">Hasil pencarian</div>
                <div className="mono" style={{ fontSize: 11, color: "var(--labs-fg-3)" }}>
                  harga indikatif · final dikonfirmasi sebelum bayar
                </div>
              </div>

              <div className="grid-3" style={{ gap: 12 }}>
                {TLD_META.map((t) => {
                  const selected = !!cart.find((c) => c.ext === t.ext);
                  const taken = TAKEN.has(clean) && t.ext === ".com"; // demo flavor
                  const price = markupPrice(QWORDS_BASE[t.ext]);
                  return (
                    <button key={t.ext} onClick={() => !taken && toggle(t.ext)}
                      disabled={taken}
                      style={{
                        all: "unset", cursor: taken ? "not-allowed" : "pointer",
                        padding: 18, borderRadius: 10,
                        border: `1.5px solid ${selected ? "var(--labs-accent)" : "var(--labs-line-2)"}`,
                        background: selected ? "rgba(240,208,80,0.08)" : "transparent",
                        display: "flex", flexDirection: "column", gap: 10,
                        opacity: taken ? 0.4 : 1,
                        transition: "all 150ms var(--ease-out)",
                        position: "relative",
                      }}>
                      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                        <span className="mono" style={{ fontSize: 11, color: "var(--labs-fg-3)", letterSpacing: ".12em", textTransform: "uppercase" }}>
                          {t.tag}
                        </span>
                        {selected && (
                          <span style={{
                            width: 18, height: 18, borderRadius: "50%",
                            background: "var(--labs-accent)", color: "#001933",
                            display: "flex", alignItems: "center", justifyContent: "center",
                            fontSize: 12, fontWeight: 700,
                          }}>✓</span>
                        )}
                      </div>
                      <div style={{
                        fontFamily: "var(--font-mono)", fontSize: 17, fontWeight: 600,
                        color: "var(--labs-fg)", letterSpacing: "-0.01em",
                        wordBreak: "break-all",
                      }}>
                        {clean}<span style={{ color: "var(--labs-accent)" }}>{t.ext}</span>
                      </div>
                      <div style={{ fontSize: 12, color: "var(--labs-fg-3)", lineHeight: 1.5 }}>{t.note}</div>
                      <div style={{ marginTop: "auto", paddingTop: 10, display: "flex", justifyContent: "space-between", alignItems: "baseline", borderTop: "1px solid var(--labs-line)" }}>
                        <span style={{ fontSize: 11, color: "var(--labs-fg-4)", fontFamily: "var(--font-mono)" }}>
                          {taken ? "Sudah dipakai" : "Tersedia"}
                        </span>
                        <span className="mono" style={{ fontSize: 15, fontWeight: 700, color: selected ? "var(--labs-accent)" : "var(--labs-fg)" }}>
                          {fmtIDR(price)}<span style={{ fontSize: 11, fontWeight: 500, color: "var(--labs-fg-3)" }}>/thn</span>
                        </span>
                      </div>
                    </button>
                  );
                })}
              </div>

              {cart.length > 0 && (
                <div style={{
                  marginTop: 20, padding: 20, borderRadius: 10,
                  background: "var(--labs-bg)", border: "1px solid var(--labs-accent)",
                }}>
                  <div className="eyebrow" style={{ marginBottom: 14 }}>Keranjang · {cart.length} domain</div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 16 }}>
                    {cart.map((c) => {
                      const price = markupPrice(QWORDS_BASE[c.ext]);
                      return (
                        <div key={c.ext} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
                          <div className="mono" style={{ fontSize: 15, color: "var(--labs-fg)", fontWeight: 600 }}>
                            {clean}<span style={{ color: "var(--labs-accent)" }}>{c.ext}</span>
                          </div>
                          <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                            <select value={c.year} onChange={(e) => setYear(c.ext, parseInt(e.target.value))}
                              className="field" style={{ padding: "6px 10px", fontSize: 13, width: "auto" }}>
                              {[1, 2, 3, 5].map((y) => <option key={y} value={y}>{y} tahun</option>)}
                            </select>
                            <div className="mono" style={{ fontSize: 14, color: "var(--labs-fg)", minWidth: 110, textAlign: "right" }}>
                              {fmtIDR(price * c.year)}
                            </div>
                            <button onClick={() => toggle(c.ext)}
                              style={{ all: "unset", cursor: "pointer", color: "var(--labs-fg-3)", fontSize: 16, padding: "0 6px" }}
                              title="Hapus">×</button>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                  <div className="rule" />
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginTop: 14, fontSize: 13, color: "var(--labs-fg-3)" }}>
                    <span>Subtotal</span><span className="mono">{fmtIDR(total)}</span>
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", fontSize: 13, color: "var(--labs-fg-3)" }}>
                    <span>PPN 11%</span><span className="mono">{fmtIDR(Math.round(total * PPN))}</span>
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginTop: 8, fontSize: 18, fontWeight: 700, color: "var(--labs-fg)" }}>
                    <span>Total</span><span className="mono" style={{ color: "var(--labs-accent)" }}>{fmtIDR(Math.round(total * (1 + PPN)))}</span>
                  </div>
                  <button onClick={order} className="btn btn-primary" style={{ marginTop: 18, width: "100%", justifyContent: "center" }}>
                    Lanjut order via WhatsApp →
                  </button>
                </div>
              )}
            </>
          )}

          {status === "taken" && (
            <div style={{ marginTop: 20, padding: 20, borderRadius: 10, background: "rgba(255,154,138,0.08)", border: "1px solid rgba(255,154,138,0.3)" }}>
              <div style={{ fontSize: 15, color: "#ff9a8a", fontWeight: 600 }}>
                <span className="mono">{clean}.com</span> & varian populer kemungkinan besar sudah dipakai.
              </div>
              <div style={{ fontSize: 13, color: "var(--labs-fg-2)", marginTop: 6 }}>
                Coba variasi nama (tambah prefix/suffix), atau ngobrol sama kami — kami bantu brainstorm nama yang masih available.
              </div>
            </div>
          )}

          <div className="rule" style={{ margin: "24px 0 18px" }} />
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 18, fontSize: 13, color: "var(--labs-fg-2)" }}>
            <DomainIncl icon="user" text="Domain atas nama kamu — bukan kami." />
            <DomainIncl icon="dns" text="DNS + email forwarding di-setup gratis." />
            <DomainIncl icon="bell" text="Auto-reminder 30 hari sebelum perpanjangan." />
            <DomainIncl icon="cart" text="Bisa dipisah, bisa di-bundle ke paket web." />
          </div>
        </div>

        <div style={{ marginTop: 18, textAlign: "center", fontSize: 12, color: "var(--labs-fg-4)", fontFamily: "var(--font-mono)" }}>
          Harga 12.5% di atas registrar Qwords · belum termasuk PPN 11% · dikonfirmasi final sebelum pembayaran
        </div>
      </div>
    </section>
  );
}

function DomainIncl({ icon, text }) {
  const icons = {
    user: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>,
    dns:  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="2" y="2" width="20" height="8" rx="2"/><rect x="2" y="14" width="20" height="8" rx="2"/><line x1="6" y1="6" x2="6.01" y2="6"/><line x1="6" y1="18" x2="6.01" y2="18"/></svg>,
    bell: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9M13.73 21a2 2 0 0 1-3.46 0"/></svg>,
    cart: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/></svg>,
  };
  return (
    <div style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
      <span style={{ color: "var(--labs-accent)", marginTop: 2 }}>{icons[icon]}</span>
      <span>{text}</span>
    </div>
  );
}

Object.assign(window, { DomainPicker, QWORDS_BASE, TLD_META, DOMAIN_MARKUP, markupPrice, fmtIDR });
