// Products + interactive "Design Your Shade" configurator with live estimate.
const COVER_STYLES = [
  { id: "lattice", name: "Lattice Cover", blurb: "Open-air slats — filtered light and airflow.", rate: 24, img: "assets/img/IMG_2803.png" },
  { id: "solid", name: "Solid Cover", blurb: "Full shade and rain protection.", rate: 30, img: "assets/img/IMG_3159.png" },
  { id: "louvered", name: "Louvered System", blurb: "Adjustable roof — open sky to full shade.", rate: 68, img: "assets/img/IMG_2535.png" },
  { id: "insulated", name: "Insulated Panel", blurb: "Foam-core roof — cooler and quieter.", rate: 46, img: "assets/img/IMG_0325.png" },
];
const MOUNTS = [
  { id: "attached", name: "Attached", note: "Tied to the house", factor: 1 },
  { id: "freestanding", name: "Freestanding", note: "Posts all around", factor: 1.14 },
];
const SIZES = [
  { id: "s", name: "Small", note: "≈ 10 × 12 ft", sqft: 120 },
  { id: "m", name: "Medium", note: "≈ 12 × 16 ft", sqft: 192 },
  { id: "l", name: "Large", note: "≈ 16 × 20 ft", sqft: 320 },
  { id: "xl", name: "Grand", note: "≈ 20 × 24 ft", sqft: 480 },
];
const ADDONS = [
  { id: "privacy", name: "Privacy panels", price: 900, priceBig: 1600 },
  { id: "rolldown", name: "Roll-down screens", price: 1450, priceBig: 2100 },
  { id: "lighting", name: "LED lighting", price: 1200 },
  { id: "fans", name: "Ceiling fans", price: 780 },
];
// addon price for the selected size: large/grand use priceBig when set
function addonPrice(a, size) {
  return ((size === "l" || size === "xl") && a.priceBig) ? a.priceBig : a.price;
}

// Explicit ballpark ranges [lo, hi] by style → mount → size.
// Styles/mounts not listed here fall back to the sqft formula below.
const PRICING = {
  lattice: {
    attached:     { s: [3400, 4200], m: [4200, 4800], l: [6800, 7400], xl: [10200, 11000] },
    freestanding: { s: [3800, 4600], m: [4600, 5200], l: [7200, 7800], xl: [10600, 11400] },
  },
  solid: {
    attached:     { s: [3600, 4400], m: [4400, 5000], l: [7000, 7600], xl: [10400, 11200] },
    freestanding: { s: [4000, 4800], m: [4800, 5400], l: [7400, 8000], xl: [10800, 11600] },
  },
  insulated: {
    attached:     { s: [4700, 5700], m: [5700, 6500], l: [9100, 9900], xl: [13500, 14600] },
    freestanding: { s: [5100, 6100], m: [6100, 6900], l: [9500, 10300], xl: [13900, 15000] },
  },
  louvered: {
    attached:     { s: [6600, 7200], m: [9800, 10200], l: [15600, 16400], xl: [24000, 24800] },
    freestanding: { s: [7000, 7600], m: [10200, 10600], l: [16000, 16800], xl: [24400, 25200] },
  },
};

function Chip({ active, onClick, children, sub }) {
  return (
    <button onClick={onClick}
      style={{ textAlign: "left", padding: "16px 18px", borderRadius: 3, cursor: "pointer",
        background: active ? "rgba(200,174,118,0.12)" : NP.panel2,
        border: `1px solid ${active ? NP.gold : NP.lineL}`, transition: "all .16s ease", width: "100%" }}>
      <div style={{ fontFamily: FONT.body, fontSize: 15.5, fontWeight: 700, color: active ? NP.gold : NP.textL }}>{children}</div>
      {sub && <div style={{ fontFamily: FONT.body, fontSize: 12.5, color: NP.textL2, marginTop: 3 }}>{sub}</div>}
    </button>
  );
}

function Configurator({ onQuote }) {
  const w = useW();
  const mobile = w < 768;
  const [style, setStyle] = React.useState("lattice");
  const [mount, setMount] = React.useState("attached");
  const [size, setSize] = React.useState("m");
  const [color, setColor] = React.useState("desert-sand");
  const [addons, setAddons] = React.useState([]);
  const toggleAddon = (id) => setAddons((a) => a.includes(id) ? a.filter((x) => x !== id) : [...a, id]);

  const est = React.useMemo(() => {
    const add = addons.reduce((sum, id) => { const a = ADDONS.find((x) => x.id === id); return sum + (a ? addonPrice(a, size) : 0); }, 0);
    const fixed = PRICING[style]?.[mount]?.[size];
    if (fixed) {
      return { lo: fixed[0] + add, hi: fixed[1] + add };
    }
    const st = COVER_STYLES.find((s) => s.id === style);
    const sz = SIZES.find((s) => s.id === size);
    const mt = MOUNTS.find((m) => m.id === mount);
    const total = sz.sqft * st.rate * mt.factor + add;
    const lo = Math.round((total * 0.92) / 100) * 100;
    const hi = Math.round((total * 1.12) / 100) * 100;
    return { lo, hi };
  }, [style, mount, size, addons]);

  const styleName = COVER_STYLES.find((s) => s.id === style).name;
  const summary = `${SIZES.find((s) => s.id === size).name} ${styleName} · ${MOUNTS.find((m) => m.id === mount).name}`;
  const fmt = (n) => "$" + n.toLocaleString();

  return (
    <div style={{ display: "grid", gridTemplateColumns: mobile ? "1fr" : "1.05fr 1fr", gap: 0, borderRadius: 4, overflow: "hidden", border: `1px solid ${NP.lineL}` }}>
      {/* live 3D preview */}
      <div style={{ position: "relative", minHeight: mobile ? 280 : 560, background: "radial-gradient(120% 100% at 50% 0%, #241d15 0%, #16110c 70%)" }}>
        <Pergola3D style={style} mount={mount} size={size} addons={addons} color={color} fallbackImg={COVER_STYLES.find((s) => s.id === style).img} />
        <div style={{ position: "absolute", top: 24, left: 24, display: "flex", gap: 8, flexWrap: "wrap", maxWidth: "80%", pointerEvents: "none" }}>
          {[styleName, MOUNTS.find((m) => m.id === mount).name, SIZES.find((s) => s.id === size).note, ...addons.map((id) => ADDONS.find((a) => a.id === id).name)].map((t, i) => (
            <span key={i} style={{ fontFamily: FONT.body, fontSize: 11.5, fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase",
              color: NP.textL, background: "rgba(21,17,13,0.72)", border: `1px solid ${NP.lineL}`, padding: "6px 11px", borderRadius: 999 }}>{t}</span>
          ))}
        </div>
        <div style={{ position: "absolute", top: 24, right: 24, fontFamily: FONT.body, fontSize: 11, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase",
          color: NP.textL2, background: "rgba(21,17,13,0.6)", border: `1px solid ${NP.lineL}`, padding: "6px 11px", borderRadius: 999, pointerEvents: "none" }}>↻ Drag to rotate</div>
        <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, padding: "26px 28px", pointerEvents: "none",
          background: "linear-gradient(180deg, rgba(21,17,13,0) 0%, rgba(21,17,13,0.92) 70%)" }}>
          <div style={{ fontFamily: FONT.body, fontSize: 12.5, fontWeight: 700, letterSpacing: "0.16em", textTransform: "uppercase", color: NP.gold }}>Estimated Range</div>
          <div style={{ display: "flex", alignItems: "baseline", gap: 12, marginTop: 6 }}>
            <div style={{ fontFamily: FONT.disp, fontWeight: 700, fontSize: 38, color: NP.textL, letterSpacing: "-0.01em" }}>{fmt(est.lo)} – {fmt(est.hi)}</div>
          </div>
          <div style={{ fontFamily: FONT.body, fontSize: 12.5, color: NP.textL2, marginTop: 4 }}>Ballpark only · final quote after a free on-site measure</div>
        </div>
      </div>
      {/* controls */}
      <div style={{ background: NP.panel, padding: mobile ? "28px 20px 28px" : "40px 40px 36px" }}>
        <Group label="Cover style">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            {COVER_STYLES.map((s) => <Chip key={s.id} active={style === s.id} onClick={() => setStyle(s.id)} sub={s.blurb}>{s.name}</Chip>)}
          </div>
        </Group>
        <Group label="Mounting">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            {MOUNTS.map((m) => <Chip key={m.id} active={mount === m.id} onClick={() => setMount(m.id)} sub={m.note}>{m.name}</Chip>)}
          </div>
        </Group>
        <Group label="Approx. size">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8 }}>
            {SIZES.map((s) => <Chip key={s.id} active={size === s.id} onClick={() => setSize(s.id)} sub={s.note}>{s.name}</Chip>)}
          </div>
        </Group>
        <Group label="Finish color">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
            {PERGOLA_COLORS.map((c) => (
              <button key={c.id} onClick={() => setColor(c.id)} title={c.name}
                style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 7, background: "none", border: "none", cursor: "pointer", padding: 0 }}>
                <span style={{ width: "100%", height: 38, borderRadius: 4, background: c.hex,
                  border: color === c.id ? `2px solid ${NP.gold}` : `1px solid ${NP.lineL}`,
                  boxShadow: color === c.id ? `0 0 0 3px rgba(200,174,118,0.25)` : "none", transition: "all .15s" }} />
                <span style={{ fontFamily: FONT.body, fontSize: 11, fontWeight: 600, color: color === c.id ? NP.gold : NP.textL2, textAlign: "center", lineHeight: 1.2 }}>{c.name}</span>
              </button>
            ))}
          </div>
        </Group>
        <Group label="Add-ons">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            {ADDONS.map((a) => <Chip key={a.id} active={addons.includes(a.id)} onClick={() => toggleAddon(a.id)}>{a.name}</Chip>)}
          </div>
        </Group>
        <Btn variant="solid" full style={{ marginTop: 28 }} onClick={() => onQuote({ style: styleName, summary: summary + " · " + (PERGOLA_COLORS.find((c) => c.id === color) || {}).name, est })}>Get this design quoted →</Btn>
      </div>
    </div>
  );
}

function Group({ label, children }) {
  return (
    <div style={{ marginBottom: 22 }}>
      <div style={{ fontFamily: FONT.body, fontSize: 12.5, fontWeight: 700, letterSpacing: "0.16em", textTransform: "uppercase", color: NP.textL2, marginBottom: 11 }}>{label}</div>
      {children}
    </div>
  );
}

function Products({ onQuote }) {
  return (
    <Section id="products">
      <Reveal>
        <div style={{ textAlign: "center", maxWidth: 720, margin: "0 auto 18px" }}>
          <Kicker center>Design Your Shade</Kicker>
          <h2 style={{ fontFamily: FONT.disp, fontWeight: 700, fontSize: "clamp(38px,4.4vw,56px)", textTransform: "uppercase",
            letterSpacing: "-0.015em", color: NP.textL, margin: "20px 0 16px", lineHeight: 1.02 }}>
            Build it your way.
          </h2>
          <p style={{ fontFamily: FONT.body, fontSize: 17.5, lineHeight: 1.65, color: NP.textL2 }}>
            Mix and match the structure, mounting, size, and add-ons to see a real ballpark — then send it over for a precise, no-pressure quote.
          </p>
        </div>
      </Reveal>
      <Reveal delay={120} style={{ marginTop: 52 }}>
        <Configurator onQuote={onQuote} />
      </Reveal>
    </Section>
  );
}

Object.assign(window, { Products, Configurator });
