// pickers.jsx — Pickers spécialisés du configurateur.

const { useState, useMemo } = React;

// === RoofPicker ===
const RoofPicker = ({ value, onChange }) => {
  const roofs = window.RAYCOM_DATA.roof_types;
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10 }}>
      {roofs.map(r => (
        <PickerCard
          key={r.key}
          active={value === r.key}
          onClick={() => onChange(r.key)}
          icon={r.flat ? "package" : "home"}
          title={r.label}
          sub={r.sub}
        />
      ))}
    </div>
  );
};

// === BatteryBrandPicker — GRID 3 COLS strict ===
const BatteryBrandPicker = ({ value, onChange, filter }) => {
  let brands = window.RAYCOM_DATA.battery_brands;
  if (filter) brands = brands.filter(filter);
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }}>
      {brands.map(b => {
        const active = value === b.key;
        return (
          <button
            key={b.key}
            className={`pcard brand-card ${active ? "active" : ""}`}
            onClick={() => onChange(b.key)}
            type="button"
          >
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
              <div className="logo">{b.logo_text}</div>
              {b.dim_required && (
                <Badge kind="lock" icon="lock">DIM intégré</Badge>
              )}
            </div>
            <div className="pcard-title" style={{ fontSize: 12, marginTop: 2 }}>{b.name}</div>
            <div className="pcard-sub">{b.sub}</div>
          </button>
        );
      })}
    </div>
  );
};

// === BatteryPackSelector ===
const BatteryPackSelector = ({ brand, value, onChange, viewMode }) => {
  const packs = window.RAYCOM_DATA.battery_packs[brand] || [];
  if (!packs.length) return null;
  const { fmtCAD0 } = window.RAYCAST_CALC;

  // Regrouper par type (kits, onduleurs seuls, batteries seules)
  const groups = [
    { kind: "kit",  title: "Kits complets (onduleur + batterie)", sub: "Configurations standard pré-bundlées" },
    { kind: "inv",  title: "Onduleurs seuls (sans batterie)",     sub: "Solaire pur ou ajout futur de batteries" },
    { kind: "batt", title: "Batteries seules",                    sub: "Extension à un onduleur existant" }
  ];
  const renderSpecs = (p) => {
    const bits = [];
    if (p.kw_inv > 0) bits.push(`${p.kw_inv} kW onduleur${p.onds > 1 ? ` ×${p.onds}` : ""}`);
    if (p.kwh > 0)    bits.push(`${p.kwh} kWh`);
    if (p.ls > 0)     bits.push(`LS ${p.ls} circ.`);
    return bits.join(" · ");
  };
  // Fallback : si aucun "kind" n'est défini (ex. tesla, solark, other), tout est traité comme "kit"
  const hasKinds = packs.some(p => p.kind);

  return (
    <div>
      <div className="cap" style={{ marginBottom: 8 }}>Configurations disponibles</div>
      {!hasKinds ? (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8 }}>
          {packs.map(p => {
            const active = value === p.id;
            return (
              <div key={p.id} className={`pkg-card ${active ? "active" : ""}`} onClick={() => onChange(p.id)}>
                <div className="name">{p.label}</div>
                <div className="specs">
                  {renderSpecs(p)}
                  {p.v2x && <span style={{ color: "var(--raycom-energy)", marginLeft: 4 }}>· V2X</span>}
                </div>
                {viewMode === "internal" && (
                  <div className="cost">{fmtCAD0(p.cost_inv + p.cost_batt)}</div>
                )}
              </div>
            );
          })}
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {groups.map(g => {
            const items = packs.filter(p => (p.kind || "kit") === g.kind);
            if (!items.length) return null;
            return (
              <div key={g.kind}>
                <div style={{
                  display: "flex", alignItems: "baseline", gap: 8,
                  fontSize: 11, fontWeight: 700, color: "var(--raycom-ink-light, #64748b)",
                  textTransform: "uppercase", letterSpacing: "0.06em",
                  marginBottom: 6,
                }}>
                  <span>{g.title}</span>
                  <span style={{ fontWeight: 500, textTransform: "none", letterSpacing: 0, fontSize: 11, opacity: 0.7 }}>
                    {g.sub}
                  </span>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8 }}>
                  {items.map(p => {
                    const active = value === p.id;
                    return (
                      <div key={p.id} className={`pkg-card ${active ? "active" : ""}`} onClick={() => onChange(p.id)}>
                        <div className="name">{p.label}</div>
                        <div className="specs">
                          {renderSpecs(p)}
                          {p.v2x && <span style={{ color: "var(--raycom-energy)", marginLeft: 4 }}>· V2X</span>}
                        </div>
                        {viewMode === "internal" && (
                          <div className="cost">{fmtCAD0(p.cost_inv + p.cost_batt)}</div>
                        )}
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

// === EcosystemComparison ===
const EcosystemComparison = ({ currentBrand, targetKwh, viewMode, onSwitch }) => {
  const { fmtCAD0 } = window.RAYCAST_CALC;
  // Find best equivalent pack in each ecosystem
  const ecos = ["tesla", "fox", "sig"];
  const equivalents = ecos.map(b => {
    // Comparatif sur les kits complets uniquement — pas les à-la-carte (inv seul / batt seule)
    const packs = (window.RAYCOM_DATA.battery_packs[b] || []).filter(p => (p.kind || "kit") === "kit");
    const closest = packs.reduce((best, p) =>
      !best || Math.abs(p.kwh - targetKwh) < Math.abs(best.kwh - targetKwh) ? p : best
    , null);
    return { brand: b, pack: closest };
  }).filter(e => e.pack);
  const minCost = Math.min(...equivalents.map(e => e.pack.cost_inv + e.pack.cost_batt));
  const brands = window.RAYCOM_DATA.battery_brands;

  if (viewMode !== "internal") return null;

  return (
    <div>
      <div className="cap" style={{ marginBottom: 8, display: "flex", alignItems: "center", gap: 6 }}>
        <Icon name="trending-up" size={11} /> Comparatif écosystèmes (≈ {targetKwh} kWh cible)
      </div>
      <div className="eco-grid">
        {equivalents.map(e => {
          const b = brands.find(x => x.key === e.brand);
          const cost = e.pack.cost_inv + e.pack.cost_batt;
          const isBest = cost === minCost;
          const active = currentBrand === e.brand;
          return (
            <div key={e.brand} className={`eco-card ${active ? "active" : ""}`} onClick={() => onSwitch(e.brand, e.pack.id)}>
              {isBest && <div className="best-flag"><Badge kind="best">💰 Meilleur prix</Badge></div>}
              <div className="name">{b.name}</div>
              <div className="hi">
                {e.pack.label}<br/>
                {e.pack.kw_inv} kW · {e.pack.kwh} kWh · Load shedding {e.pack.ls} circuit{e.pack.ls > 1 ? "s" : ""}
                {e.pack.v2x && <><br/><span style={{ color: "var(--raycom-energy)" }}>V2X compatible</span></>}
              </div>
              <div className="cost" style={{ color: isBest ? "var(--raycom-energy)" : "var(--raycom-ink)" }}>
                {fmtCAD0(cost)}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

// === BackupModePicker ===
const BackupModePicker = ({ value, onChange, serviceAmperage, viewMode, hasBattery }) => {
  const { fmtCAD0 } = window.RAYCAST_CALC;
  if (!hasBattery) return null;
  // Règle métier : si batterie → toujours partial ou whole_home (pas de "mesurage net seul")
  const modes = window.RAYCOM_DATA.backup_modes.filter(m => !m.requires_battery === false ? true : m.key !== "none");
  // Forcer un mode valide si "none" est encore sélectionné avec batterie
  React.useEffect(() => {
    if (hasBattery && value === "none") onChange("partial");
  }, [hasBattery, value]);
  return (
    <div>
      <div className="cap" style={{ marginBottom: 8 }}>Mode de backup — un système avec batterie alimente toujours soit les charges critiques, soit la maison au complet</div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
        {modes.map(m => {
          const disabled = m.key === "whole_home" && serviceAmperage > 200;
          const active = value === m.key;
          let delta = m.delta;
          if (m.key === "whole_home" && serviceAmperage > 200) delta = 1200;
          return (
            <div key={m.key} className={`pcard ${active && !disabled ? "active" : ""} ${disabled ? "disabled" : ""}`} onClick={() => !disabled && onChange(m.key)}>
              <div className="pcard-title">{m.label}</div>
              <div className="pcard-sub">
                {disabled ? "Entrée > 200 A — ATS commercial requis" : m.sub}
              </div>
              {viewMode === "internal" && !disabled && (
                <div style={{ fontSize: 11, fontWeight: 700, color: delta > 0 ? "var(--margin-yellow)" : "var(--raycom-energy)", marginTop: 4, fontVariantNumeric: "tabular-nums" }}>
                  {delta > 0 ? `+${fmtCAD0(delta)} ATS commercial` : "Inclus au forfait"}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

// === EvChargerSection ===
const EvChargerSection = ({ ve, setVe, viewMode, building }) => {
  const { fmtCAD0 } = window.RAYCAST_CALC;
  const bornes = window.RAYCOM_DATA.bornes;
  const isMulti = building === "multilog";
  const selected = ve.bornes_selected || [];
  const isSelected = (k) => selected.find(s => s.key === k);

  const toggleBorne = (k) => {
    const idx = selected.findIndex(s => s.key === k);
    let next;
    if (idx >= 0) next = selected.filter(s => s.key !== k);
    else next = [...selected, { key: k, qty: 1 }];
    setVe({ ...ve, bornes_selected: next });
  };
  const setQty = (k, q) => {
    setVe({ ...ve, bornes_selected: selected.map(s => s.key === k ? { ...s, qty: q } : s) });
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div>
        <div className="cap" style={{ marginBottom: 8 }}>Catalogue bornes niveau 2</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }}>
          {bornes.map(b => {
            const sel = isSelected(b.key);
            return (
              <div key={b.key} className={`pcard brand-card ${sel ? "active" : ""}`} onClick={() => toggleBorne(b.key)}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 6 }}>
                  <Icon name="plug" size={16} color="var(--raycom-accent-dark)" />
                  {b.v2x && <Badge kind="green">V2X</Badge>}
                </div>
                <div className="pcard-title" style={{ fontSize: 11.5 }}>{b.brand}</div>
                <div className="pcard-sub">{b.model}</div>
                <div className="pcard-sub" style={{ fontFamily: "Fragment Mono, monospace" }}>{b.connector} · {b.kw} kW</div>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: "auto", paddingTop: 4 }}>
                  {b.rve && <Badge kind="green">RVÉ</Badge>}
                  {viewMode === "internal" && b.price > 0 && (
                    <span style={{ fontSize: 11, fontWeight: 700, fontVariantNumeric: "tabular-nums", color: "var(--raycom-ink)" }}>
                      {fmtCAD0(b.price)}
                    </span>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {selected.length > 0 && (
        <div className="live-preview">
          <div className="cap" style={{ marginBottom: 6 }}>Quantités sélectionnées</div>
          {selected.map(s => {
            const b = bornes.find(x => x.key === s.key);
            return (
              <div key={s.key} className="row">
                <span className="k">{b.brand} {b.model}</span>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                  <button className="btn-ghost" style={{ padding: "2px 6px" }} onClick={() => setQty(s.key, Math.max(1, s.qty - 1))}><Icon name="minus" size={10}/></button>
                  <span className="v" style={{ minWidth: 16, textAlign: "center" }}>{s.qty}</span>
                  <button className="btn-ghost" style={{ padding: "2px 6px" }} onClick={() => setQty(s.key, Math.min(isMulti ? 8 : 4, s.qty + 1))}><Icon name="plus" size={10}/></button>
                </span>
              </div>
            );
          })}
        </div>
      )}

      <div className="grid2">
        <label className="field">
          <span className="lbl">Longueur câble (pi)</span>
          <RCSlider
            value={ve.cable_length_pi}
            min={25} max={150} step={5}
            suffix=" pi"
            onChange={(v) => setVe({ ...ve, cable_length_pi: v })}
            hint={<><span>50 pi inclus · surcharge 18 $/pi au-delà</span><span></span></>}
          />
        </label>
        <label className="field">
          <span className="lbl">Scénario d'installation</span>
          <SegmentedToggle
            value={ve.scenario_post_2018 ? "post" : "neuf"}
            options={[
              { value: "post", label: "Préfilage 2018+" },
              { value: "neuf", label: "Fil neuf" }
            ]}
            onChange={(v) => setVe({ ...ve, scenario_post_2018: v === "post" })}
          />
        </label>
      </div>

      <div>
        <div className="cap" style={{ marginBottom: 8 }}>Dispositif de contrôle de charge (DCC)</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }}>
          {["aucun", "dcc12", "dsdc"].map(opt => {
            const labels = { aucun: ["Aucun", "Installation simple ≤ entrée actuelle"], dcc12: ["DCC-12 (RVE)", "Borne 40 A sans hausse de service · obligatoire multilog/condo"], dsdc: ["Tesla DSDC", "Remote Meter Tesla · NACS uniquement"] };
            const lockOn = (building === "multilog") && opt === "aucun";
            return (
              <div key={opt} className={`pcard ${ve.dcc_option === opt ? "active" : ""} ${lockOn ? "disabled" : ""}`} onClick={() => !lockOn && setVe({ ...ve, dcc_option: opt })}>
                <div className="pcard-title">{labels[opt][0]}</div>
                <div className="pcard-sub">{lockOn ? "Verrouillé — multilog requiert DCC" : labels[opt][1]}</div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { RoofPicker, BatteryBrandPicker, BatteryPackSelector, EcosystemComparison, BackupModePicker, EvChargerSection });
