// ============================================================
//  Shipping — Japan Post International Air Packet
//  Standardised around the 1 kg rate ("1 kit ≈ 1 kg")
//  Renders into #root
// ============================================================
const { useState, useMemo, useEffect } = React;

const SHOP_EMAIL = "inquiry@takarascale.jp";

// ---- zones (Japan Post International Air Packet, from 2026-06-01) ----
const ZONES = [
  { id: 1, name: "Zone 1", blurb: "China · South Korea · Taiwan",
    countries: ["China", "South Korea", "Taiwan"] },
  { id: 2, name: "Zone 2", blurb: "Rest of Asia",
    countries: ["Hong Kong", "Singapore", "Thailand", "Malaysia", "Vietnam", "Philippines", "Indonesia", "India", "UAE? (see note)"] },
  { id: 3, name: "Zone 3", blurb: "Europe · Oceania · Canada · Mexico · Middle East",
    countries: ["United Kingdom", "Germany", "France", "Italy", "Spain", "Netherlands", "Belgium", "Switzerland", "Sweden", "Australia", "New Zealand", "Canada", "Mexico", "UAE", "Saudi Arabia"] },
  { id: 4, name: "Zone 4", blurb: "United States (incl. territories)",
    countries: ["United States", "Guam", "Puerto Rico", "Hawaii"] },
  { id: 5, name: "Zone 5", blurb: "Latin America (excl. Mexico) · Africa",
    countries: ["Brazil", "Argentina", "Chile", "South Africa", "Egypt", "Kenya", "Nigeria"] },
];

// full rate table: weight(g cap) -> [z1,z2,z3,z4,z5] (incl. ¥370 tracking)
const RATES = [
  [100, 720, 750, 880, 1200, 920],
  [200, 820, 870, 1060, 1410, 1180],
  [300, 920, 990, 1240, 1620, 1440],
  [400, 1020, 1110, 1420, 1830, 1700],
  [500, 1120, 1230, 1600, 2040, 1960],
  [600, 1220, 1350, 1780, 2250, 2220],
  [700, 1320, 1470, 1960, 2460, 2480],
  [800, 1420, 1590, 2140, 2670, 2740],
  [900, 1520, 1710, 2320, 2880, 3000],
  [1000, 1620, 1830, 2500, 3090, 3260],
  [1100, 1720, 1950, 2680, 3300, 3520],
  [1200, 1820, 2070, 2860, 3510, 3780],
  [1300, 1920, 2190, 3040, 3720, 4040],
  [1400, 2020, 2310, 3220, 3930, 4300],
  [1500, 2120, 2430, 3400, 4140, 4560],
  [1600, 2220, 2550, 3580, 4350, 4820],
  [1700, 2320, 2670, 3760, 4560, 5080],
  [1800, 2420, 2790, 3940, 4770, 5340],
  [1900, 2520, 2910, 4120, 4980, 5600],
  [2000, 2620, 3030, 4300, 5190, 5860],
];

const STD_WEIGHT = 1000;             // 1 kit ≈ 1 kg packed
const stdRow = RATES.find((r) => r[0] === STD_WEIGHT);

// ---- currency (foreign only; default USD — JPY not shown on this page) ----
const CURRENCIES = {
  USD: { sym: "$",  perYen: 1 / 150,  label: "$ USD" },
  EUR: { sym: "€",  perYen: 1 / 165,  label: "€ EUR" },
  GBP: { sym: "£",  perYen: 1 / 190,  label: "£ GBP" },
  AUD: { sym: "A$", perYen: 1 / 100,  label: "A$ AUD" },
  CAD: { sym: "C$", perYen: 1 / 110,  label: "C$ CAD" },
};
const CURRENCY_KEYS = Object.keys(CURRENCIES);
let activeCur = "USD"; // set by <ShippingPage> each render

function applyRates(rates) {
  for (const k of CURRENCY_KEYS) {
    if (typeof rates[k] === "number" && rates[k] > 0) CURRENCIES[k].perYen = rates[k];
  }
}
async function loadRates() {
  const now = Date.now();
  try {
    const cached = JSON.parse(localStorage.getItem("tsa_rates") || "null");
    if (cached && cached.r && now - cached.t < 12 * 3600 * 1000) { applyRates(cached.r); return true; }
  } catch (e) {}
  try {
    const res = await fetch("https://open.er-api.com/v6/latest/JPY");
    const data = await res.json();
    if (data && data.rates) { applyRates(data.rates); try { localStorage.setItem("tsa_rates", JSON.stringify({ t: now, r: data.rates })); } catch (e) {} return true; }
  } catch (e) {}
  return false;
}

// money() — selected (foreign) currency, no decimals; tidy rounding
function money(n) {
  if (n == null) return "—";
  const c = CURRENCIES[activeCur] || CURRENCIES.USD;
  const v = n * c.perYen;
  const r = v >= 50 ? Math.round(v / 5) * 5 : Math.round(v);
  return c.sym + r.toLocaleString("en-US");
}

// rate for a given total grams + zone index (1-based)
function rateFor(grams, zoneId) {
  const row = RATES.find((r) => grams <= r[0]);
  if (!row) return null;            // over 2 kg
  return row[zoneId];
}

// ---------- header / footer ----------
function SiteHeader() {
  return (
    <header className="site">
      <div className="wrap nav">
        <a href="Takara Scale Agency.html" className="brand">
          <svg className="brand-logo" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
            <defs><clipPath id="blClipS"><circle cx="20" cy="20" r="19" /></clipPath></defs>
            <g clipPath="url(#blClipS)">
              <rect width="40" height="40" fill="#f4f2ec" />
              <circle cx="20" cy="15.5" r="7.4" fill="#cf2f2c" />
              <path d="M1 35 L20 17.5 L39 35 Z" fill="#2a2a2a" />
              <path d="M20 17.5 L15.6 21.5 L17.7 20.4 L20 22 L22.3 20.4 L24.4 21.5 Z" fill="#fff" />
            </g>
            <circle cx="20" cy="20" r="19" fill="none" stroke="#2a2a2a" strokeOpacity="0.12" strokeWidth="1.4" />
          </svg>
          <span className="bt">
            <span className="mark">TAKARA SCALE AGENCY</span>
            <span className="sub">Worldwide shipping from Japan</span>
          </span>
        </a>
        <nav className="nav-links">
          <a href="Takara Scale Agency.html#stock">Stock</a>
          <a href="Modeler's Tools.html">Tools</a>
          <a href="Shipping.html" className="cur">Shipping</a>
          <a href="Takara Scale Agency.html#ask">Ask</a>
        </nav>
        <div className="nav-right">
          <a className="btn btn--sm" href="Takara Scale Agency.html#stock">Back to store</a>
        </div>
      </div>
    </header>
  );
}

function SiteFooter() {
  return (
    <footer className="site">
      <div className="wrap">
        <div className="foot-bottom">
          <span>© {new Date().getFullYear()} TAKARA SCALE AGENCY · Ships worldwide from Japan</span>
          <span>Japan Post · International Air Packet · Tracked</span>
        </div>
      </div>
    </footer>
  );
}

// ---------- calculator ----------
function Calculator() {
  const [zoneId, setZoneId] = useState(4);
  const [kits, setKits] = useState(1);
  const grams = kits * STD_WEIGHT;
  const overLimit = grams > 2000;
  const rate = rateFor(grams, zoneId);
  const perKit = rateFor(STD_WEIGHT, zoneId);
  const zone = ZONES.find((z) => z.id === zoneId);

  return (
    <div className="calc">
      <div className="calc-controls">
        <div className="fld">
          <span>Destination</span>
          <select value={zoneId} onChange={(e) => setZoneId(Number(e.target.value))}>
            {ZONES.map((z) => <option key={z.id} value={z.id}>{z.name} — {z.blurb}</option>)}
          </select>
        </div>
        <div className="fld">
          <span>Number of kits</span>
          <div className="stepper">
            <button onClick={() => setKits((k) => Math.max(1, k - 1))} aria-label="less">−</button>
            <b>{kits}</b>
            <button onClick={() => setKits((k) => k + 1)} aria-label="more">+</button>
          </div>
        </div>
      </div>

      <div className={"calc-out" + (overLimit ? " calc-out--warn" : "")}>
        {!overLimit ? (
          <React.Fragment>
            <div className="calc-out-main">
              <span className="calc-out-k">Estimated shipping · {zone.name}</span>
              <span className="calc-out-v">{money(rate)}</span>
            </div>
            <div className="calc-out-detail">
              <span>{kits} kit{kits > 1 ? "s" : ""}</span>
              <span>Flat per-kit rate: <b>{money(perKit)}</b></span>
              <span>Fully tracked · all-inclusive</span>
            </div>
          </React.Fragment>
        ) : (
          <div className="calc-warn">
            <b>More than 2 kits in one packet.</b>
            <p>{kits} kits exceed a single packet. We split larger orders into multiple tracked packets or quote International Parcel / EMS — just ask and we'll work out the cheapest combination for your country.</p>
            <a className="btn btn--red btn--sm" href="index.html#ask">Get a combined quote →</a>
          </div>
        )}
      </div>
      <p className="calc-note">
        Based on Japan Post International&nbsp;Air&nbsp;Packet (fully tracked). <b>One flat rate per kit</b> — final cost is confirmed by email before you pay; USD figures are indicative only.
      </p>
    </div>
  );
}

// ---------- full rate table ----------
function RateTable() {
  const kitRows = [1, 2]; // one Air Packet holds up to 2 kits
  return (
    <div className="rate-wrap">
      <div className="rate-scroll">
        <table className="rate">
          <thead>
            <tr>
              <th>Per order</th>
              {ZONES.map((z) => (
                <th key={z.id}>
                  <b>{z.name}</b>
                  <span>{z.blurb}</span>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {kitRows.map((k) => (
              <tr key={k} className={k === 1 ? "std" : ""}>
                <td className="rate-w">
                  {k} kit{k > 1 ? "s" : ""}
                  {k === 1 && <em>standard</em>}
                </td>
                {ZONES.map((z) => <td key={z.id}>{money(rateFor(STD_WEIGHT * k, z.id))}</td>)}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <p className="rate-foot">Japan Post International Air Packet, effective 1 June 2026. Rates include international tracking. Orders of 3+ kits ship as multiple tracked packets — ask for a combined quote.</p>
    </div>
  );
}

// ---------- page ----------
function ShippingPage() {
  const [currency, setCurrency] = useState(() => {
    try { const s = localStorage.getItem("tsa_cur"); if (s && CURRENCIES[s]) return s; } catch (e) {}
    return "USD"; // default to USD on the shipping page
  });
  activeCur = currency;
  const [, bump] = useState(0);
  useEffect(() => { try { localStorage.setItem("tsa_cur", currency); } catch (e) {} }, [currency]);
  useEffect(() => { loadRates().then((ok) => { if (ok) bump((n) => n + 1); }); }, []);

  return (
    <React.Fragment>
      <div className="topbar">
        <div className="wrap">
          <span className="sun-mini"></span>
          <span>Worldwide shipping from Japan · <b>One flat per-kit rate, tracked door to mailbox</b></span>
        </div>
      </div>
      <SiteHeader />

      <section className="s-hero">
        <div className="rays"></div>
        <div className="wrap">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
            <span className="eyebrow">Shipping</span>
            <label style={{ fontSize: 13, color: "var(--ink-2)", display: "inline-flex", alignItems: "center", gap: 8 }}>
              Currency
              <select value={currency} onChange={(e) => setCurrency(e.target.value)} aria-label="Display currency"
                style={{ background: "transparent", border: "1px solid var(--line)", borderRadius: 8, padding: "6px 8px", font: "inherit", fontSize: 13, cursor: "pointer", color: "inherit" }}>
                {CURRENCY_KEYS.map((k) => <option key={k} value={k}>{CURRENCIES[k].label}</option>)}
              </select>
            </label>
          </div>
          <h1>One kit, <em>one flat rate.</em></h1>
          <p>We ship worldwide with Japan&nbsp;Post International&nbsp;Air&nbsp;Packet — fully tracked, delivered to your mailbox. <b>One simple price per kit</b>, no surprises at checkout — and typically <b>well below what eBay charges</b> for the same kit sent from Japan.</p>
        </div>
      </section>

      {/* standardised per-kit rate strip */}
      <section className="wrap std-strip-wrap">
        <div className="std-head">
          <h2>The standard rate — per kit</h2>
          <p>This is what one kit costs to ship, by region. No surprises at checkout — and usually cheaper than eBay's Japan shipping.</p>
        </div>
        <div className="std-strip">
          {ZONES.map((z, i) => (
            <div className={"std-card" + (z.id === 4 ? " std-card--hl" : "")} key={z.id}>
              <span className="std-zone">{z.name}</span>
              <span className="std-blurb">{z.blurb}</span>
              <span className="std-rate">{money(stdRow[i + 1])}</span>
              <span className="std-usd">per kit</span>
            </div>
          ))}
        </div>
      </section>

      <section className="wrap s-section">
        <div className="s-grid">
          <div className="s-block">
            <h3>Estimate your shipping</h3>
            <p className="s-sub">Pick your region and how many kits — one flat rate per kit.</p>
            <Calculator />
          </div>
          <aside className="s-aside">
            <h4>How it works</h4>
            <ol className="s-steps">
              <li><b>You order or join a waiting list.</b> We confirm the kit, condition photos and the exact shipping total by email.</li>
              <li><b>We pack heavy.</b> Sealed kits are double-boxed with the original box protected — corners and decals matter to collectors.</li>
              <li><b>Tracked all the way.</b> Every parcel ships with Japan&nbsp;Post tracking and is delivered to your mailbox; no signature needed unless taxed.</li>
              <li><b>Customs &amp; duties.</b> Import duties/VAT are the buyer's responsibility and vary by country. We declare honestly with the correct contents.</li>
            </ol>
            <div className="s-spec">
              <h4>Per packet</h4>
              <ul>
                <li><span>Kits per packet</span><b>Up to 2</b></li>
                <li><span>Max size</span><b>L+W+H ≤ 90 cm</b></li>
                <li><span>Max length</span><b>60 cm</b></li>
                <li><span>Tracking</span><b>Included</b></li>
              </ul>
              <p className="s-spec-note">Orders of 3&nbsp;kits or more ship as multiple tracked packets or International&nbsp;Parcel / EMS — we always quote the cheapest option for your country.</p>
            </div>
          </aside>
        </div>
      </section>

      <section className="wrap s-section">
        <div className="s-block">
          <h3>Full rate table</h3>
          <p className="s-sub">Every shipping price, per kit, by region — fully tracked.</p>
          <RateTable />
        </div>
      </section>

      <section className="s-cta">
        <div className="wrap">
          <h2>Ready to send one home?</h2>
          <p>Find a kit in stock and we'll confirm your all-in total — kit plus shipping — before you pay anything.</p>
          <div className="s-cta-btns">
            <a className="btn btn--red" href="Takara Scale Agency.html#stock">Browse the collection →</a>
            <a className="btn btn--ghost" href="index.html#ask">Ask a shipping question</a>
          </div>
        </div>
      </section>

      <SiteFooter />
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<ShippingPage />);
