/* global React, Shot, Reveal */

const ZAR = (n) => "R " + Math.round(n).toLocaleString("en-ZA");

/* base + option catalogue. Prices are placeholders — edit freely. */
const BASE_PRICE = 577367;

const HULLS = [
  { id: "graphite", name: "Graphite", hex: "#2b2f33", add: 0, filter: "saturate(0.12) brightness(0.82)" },
  { id: "cobalt", name: "Caerula Blue", hex: "#1f3aa6", add: 0, filter: "saturate(1.1) brightness(1.12)" },
  { id: "storm", name: "Storm Grey", hex: "#6c757b", add: 0, filter: "saturate(0.18) brightness(1.28)" },
  { id: "bone", name: "Bone White", hex: "#e8e6df", add: 0, filter: "saturate(0.08) brightness(1.72)" },
  { id: "abyss", name: "Abyss Black", hex: "#0d0f10", add: 18000, filter: "saturate(0.22) brightness(0.42)" },
  { id: "kelp", name: "Kelp Green", hex: "#3f5a45", add: 24000, filter: "hue-rotate(-115deg) saturate(0.85) brightness(1.0)" },
];

const CATEGORIES = [
  {
    id: "power", title: "Power", req: true,
    options: [
      { id: "twin90", name: "Twin 90 HP", desc: "Minimum rig — light and economical", add: 520000 },
      { id: "twin115", name: "Twin 115 HP", desc: "Recommended — the sea-trialled sweet spot", add: 610000 },
      { id: "twin140", name: "Twin 140 HP", desc: "Maximum power — full offshore pace", add: 720000 },
    ],
  },
  {
    id: "ttop", title: "T-Top", req: true,
    options: [
      { id: "none", name: "Open Console", desc: "Clean, minimal, lightweight", add: 0 },
      { id: "alu", name: "Alloy T-Top", desc: "Powder-coated marine alloy + rod holders", add: 62000 },
      { id: "carbon", name: "Carbon Hard-Top", desc: "Carbon canopy, LED, electronics box", add: 138000 },
    ],
  },
  {
    id: "electronics", title: "Electronics", req: true,
    options: [
      { id: "core", name: "Core Nav", desc: "9\" plotter, VHF, basic sounder", add: 0 },
      { id: "offshore", name: "Offshore Suite", desc: "Dual 12\" displays, radar-ready, AIS", add: 96000 },
      { id: "apex", name: "Apex Sonar", desc: "Live sonar, autopilot, 360° radar", add: 184000 },
    ],
  },
  {
    id: "seating", title: "Seating Layout",
    options: [
      { id: "lean", name: "Lean Post", desc: "Twin lean post, max deck space", add: 0 },
      { id: "bolster", name: "Bolster Helm", desc: "Folding bolster seats, fore seating", add: 38000 },
      { id: "lounge", name: "Bow Lounge", desc: "Wraparound bow lounge + filler", add: 74000 },
    ],
  },
  {
    id: "fishing", title: "Fishing Package",
    options: [
      { id: "std", name: "Standard", desc: "4 rod holders, baitwell", add: 0 },
      { id: "sport", name: "Sport Angler", desc: "Live well, 8 holders, rocket launcher", add: 52000 },
      { id: "tournament", name: "Tournament", desc: "Twin live wells, outriggers, tuna door", add: 118000 },
    ],
  },
  {
    id: "deck", title: "Deck Configuration",
    options: [
      { id: "open", name: "Open Fishing Deck", desc: "Uncluttered, self-draining", add: 0 },
      { id: "dive", name: "Dive / Adventure", desc: "Dive ladder, wash-down, gear racks", add: 44000 },
    ],
  },
  {
    id: "trailer", title: "Trailer",
    options: [
      { id: "none", name: "No Trailer", desc: "Collection / berth delivery", add: 0 },
      { id: "single", name: "Tandem Galv.", desc: "Hot-dip galvanised, braked", add: 68000 },
      { id: "alko", name: "Off-Road Tri-Axle", desc: "Tri-axle, off-road, full spare", add: 124000 },
    ],
  },
  {
    id: "storage", title: "Storage Upgrade", multi: true,
    options: [
      { id: "underdeck", name: "Under-deck lockers", desc: "Sealed dry storage", add: 22000 },
      { id: "rodlocker", name: "Lockable rod locker", desc: "In-gunwale, 8 ft", add: 17000 },
      { id: "cooler", name: "Insulated fish hold", desc: "120 L keep-cold", add: 26000 },
    ],
  },
  {
    id: "luxury", title: "Luxury Upgrades", multi: true,
    options: [
      { id: "audio", name: "Marine audio", desc: "Amp + 6 speakers + sub", add: 34000 },
      { id: "fridge", name: "Console fridge", desc: "Drawer fridge / freezer", add: 21000 },
      { id: "head", name: "Console head", desc: "Enclosed marine toilet", add: 39000 },
      { id: "uphol", name: "Premium upholstery", desc: "Diamond-stitch, UV-rated", add: 28000 },
    ],
  },
];

function priceOf(state) {
  let total = BASE_PRICE;
  const hull = HULLS.find((h) => h.id === state.hull);
  if (hull) total += hull.add;
  CATEGORIES.forEach((c) => {
    if (c.multi) {
      (state[c.id] || []).forEach((oid) => {
        const o = c.options.find((x) => x.id === oid);
        if (o) total += o.add;
      });
    } else {
      const o = c.options.find((x) => x.id === state[c.id]);
      if (o) total += o.add;
    }
  });
  return total;
}

function defaultState() {
  const s = { hull: "graphite" };
  CATEGORIES.forEach((c) => { s[c.id] = c.multi ? [] : c.options[0].id; });
  return s;
}

function Configurator() {
  const [state, setState] = useState(defaultState);
  const [active, setActive] = useState("power");
  const total = priceOf(state);
  const hull = HULLS.find((h) => h.id === state.hull);

  const pick = (cid, oid, multi) => {
    setState((s) => {
      if (multi) {
        const cur = s[cid] || [];
        return { ...s, [cid]: cur.includes(oid) ? cur.filter((x) => x !== oid) : [...cur, oid] };
      }
      return { ...s, [cid]: oid };
    });
  };

  return (
    <section className="section build" id="build">
      <div className="wrap">
        <div className="build__head">
          <Reveal><div className="eyebrow">02 — Build Your Nemesis</div></Reveal>
          <Reveal delay={1}><h2 className="h-xl">Configure every detail.</h2></Reveal>
          <Reveal delay={2}><p className="lead">Specify your boat the way you'd order a performance vehicle.
            Pricing updates live. When it's right, send it to our team to confirm your build.</p></Reveal>
        </div>

        <div className="build__layout">
          {/* LEFT — live preview + hull */}
          <div className="build__preview">
            <div className="preview__frame">
              <div className="preview__stage scene-dawn">
                <div className="preview__glow" style={{ background: `radial-gradient(58% 46% at 50% 64%, ${hull.hex}66, transparent 72%)` }}></div>
                <img className="preview__boat" src="assets/nemesis-render.png" alt={`Nemesis 2200 — ${hull.name} hull`} style={{ filter: hull.filter }} />
                <div className="preview__grain"></div>
                <div className="shot__corner">CONFIG</div>
                <div className="shot__label">{`${hull.name.toLowerCase()} hull · ${state.power === "twin140" ? "twin 140hp" : state.power === "twin115" ? "twin 115hp" : "twin 90hp"}`}</div>
                <div className="preview__hullchip" style={{ background: hull.hex, color: hull.id === "bone" ? "#222" : "#fff" }}>{hull.name}</div>
              </div>
            </div>

            <div className="hulls">
              <div className="hulls__label tag">Hull Colour</div>
              <div className="hulls__row">
                {HULLS.map((h) => (
                  <button key={h.id} className={`swatch ${state.hull === h.id ? "on" : ""}`} onClick={() => setState((s) => ({ ...s, hull: h.id }))} title={h.name}>
                    <span className="swatch__dot" style={{ background: h.hex }}></span>
                    <span className="swatch__name">{h.name}</span>
                    {h.add > 0 && <span className="swatch__add mono">+{(h.add/1000)}k</span>}
                  </button>
                ))}
              </div>
            </div>

            <div className="build__summary">
              <div className="summary__row"><span className="tag">Base · Nemesis 2200</span><span className="mono">{ZAR(BASE_PRICE)}</span></div>
              <div className="summary__line"></div>
              {hull.add > 0 && <div className="summary__row sm"><span>{hull.name} hull</span><span className="mono">+{ZAR(hull.add)}</span></div>}
              {CATEGORIES.map((c) => {
                if (c.multi) {
                  return (state[c.id] || []).map((oid) => {
                    const o = c.options.find((x) => x.id === oid);
                    return <div key={c.id + oid} className="summary__row sm"><span>{o.name}</span><span className="mono">+{ZAR(o.add)}</span></div>;
                  });
                }
                const o = c.options.find((x) => x.id === state[c.id]);
                if (!o || o.add === 0) return null;
                return <div key={c.id} className="summary__row sm"><span>{o.name}</span><span className="mono">+{ZAR(o.add)}</span></div>;
              })}
              <div className="summary__line"></div>
              <div className="summary__total">
                <span className="tag">Est. total <em>excl. VAT</em></span>
                <span className="summary__price">{ZAR(total)}</span>
              </div>
              <a href="#contact" onClick={(e) => { e.preventDefault(); document.getElementById("contact")?.scrollIntoView({ behavior: "smooth" }); }} className="btn btn-primary btn-block">Send This Build to Bromley<span className="arr">→</span></a>
            </div>
          </div>

          {/* RIGHT — option categories */}
          <div className="build__options">
            {CATEGORIES.map((c) => {
              const isOpen = active === c.id;
              const sel = c.multi ? (state[c.id] || []) : [state[c.id]];
              const selName = c.multi
                ? (sel.length ? `${sel.length} selected` : "None")
                : c.options.find((o) => o.id === state[c.id])?.name;
              return (
                <div key={c.id} className={`optgroup ${isOpen ? "open" : ""}`}>
                  <button className="optgroup__head" onClick={() => setActive(isOpen ? null : c.id)}>
                    <span className="optgroup__title">{c.title}{c.req && <i className="req">required</i>}</span>
                    <span className="optgroup__cur mono">{selName}<span className="chev">⌄</span></span>
                  </button>
                  <div className="optgroup__body">
                    <div className="optgroup__grid">
                      {c.options.map((o) => {
                        const on = c.multi ? sel.includes(o.id) : state[c.id] === o.id;
                        return (
                          <button key={o.id} className={`opt ${on ? "on" : ""}`} onClick={() => pick(c.id, o.id, c.multi)}>
                            <div className="opt__top">
                              <span className="opt__name">{o.name}</span>
                              <span className="opt__add mono">{o.add === 0 ? "Incl." : "+" + ZAR(o.add)}</span>
                            </div>
                            <div className="opt__desc">{o.desc}</div>
                            <span className="opt__check">{on ? "✓" : ""}</span>
                          </button>
                        );
                      })}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Configurator });
