/* Shipments — FBA shipment tracking (Canada → Amazon centres) */

const SHIPMENT_STATUSES = [
  { id: "préparation", label: "Préparation", tone: "muted", icon: "cube" },
  { id: "en transit",  label: "En transit",  tone: "blue",  icon: "truck" },
  { id: "douanes",     label: "Douanes",     tone: "amber", icon: "shield" },
  { id: "réception",   label: "Réception",   tone: "green", icon: "check" },
];

const ShipmentRow = ({ s, onSave, onDelete }) => {
  const status = SHIPMENT_STATUSES.find(x => x.id === s.status) || SHIPMENT_STATUSES[0];
  return (
    <tr>
      <td className="mono" style={{ fontWeight: 600 }}>{s.id}</td>
      <td>
        <div style={{ fontSize: 12.5 }}>
          <EditableField value={s.origin} onSave={(v) => onSave(s.id, { origin: v })} width={160}/>
        </div>
        <div className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)" }}>
          <Icon name="chevron-right" size={10} style={{ verticalAlign: "-1px" }} />{" "}
          <EditableField value={s.dest} onSave={(v) => onSave(s.id, { dest: v })} width={160}/>
        </div>
      </td>
      <td className="mono" style={{ fontVariantNumeric: "tabular-nums" }}>
        <EditableField value={s.units} onSave={(v) => onSave(s.id, { units: Number(v) || 0 })} type="number" format={(v) => Number(v).toLocaleString()} width={80}/>
      </td>
      <td>
        <EditableField value={s.carrier} onSave={(v) => onSave(s.id, { carrier: v })} width={120}/>
      </td>
      <td>
        <EditableField
          value={s.status}
          onSave={(v) => onSave(s.id, { status: v })}
          options={SHIPMENT_STATUSES.map(st => ({ value: st.id, label: st.label }))}
          format={(v) => {
            const st = SHIPMENT_STATUSES.find(x => x.id === v) || SHIPMENT_STATUSES[0];
            return <Badge tone={st.tone} dot><Icon name={st.icon} size={11} style={{ marginRight: 4 }} /> {st.label}</Badge>;
          }}
          width={140}
        />
      </td>
      <td className="mono">
        <EditableField value={s.eta} onSave={(v) => onSave(s.id, { eta: v })} width={120}/>
      </td>
      <td>
        <button
          className="btn" data-variant="ghost" data-size="sm"
          title="Mettre à la corbeille"
          onClick={() => onDelete && onDelete(s)}
          style={{ color: "var(--red)" }}
        >
          <Icon name="x" size={11}/>
        </button>
      </td>
    </tr>
  );
};

const Shipments = () => {
  const [tab, setTab] = useState("all");
  const [, force] = useState(0);
  const toast = (window.useToast || (() => () => {}))();
  const trashHook = (window.useKCCTrash || (() => ({ items: [], send: async () => {} })))();

  const [newOpen, setNewOpen] = useState(false);
  const [draft, setDraft] = useState({ name: "", dest: "", status: "préparation", eta: "", units: 0, value: 0 });

  const persistShipment = async (id, patch) => {
    const s = SHIPMENTS.find(x => x.id === id);
    if (!s) return;
    Object.assign(s, patch);
    force(x => x + 1);
    try {
      await fetch("/api/sync", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ col: "shipments", items: [{ ...s }] }),
      });
    } catch (_) {}
  };

  const create = async () => {
    if (!draft.name?.trim()) return;
    const id = "FBA-" + Date.now().toString(36).toUpperCase();
    const fresh = {
      id,
      name: draft.name.trim(),
      origin: "—",
      dest: draft.dest.trim() || "—",
      status: draft.status || "préparation",
      eta: draft.eta.trim() || "—",
      units: Number(draft.units) || 0,
      value: Number(draft.value) || 0,
      carrier: "—",
    };
    SHIPMENTS.push(fresh);
    setNewOpen(false);
    setDraft({ name: "", dest: "", status: "préparation", eta: "", units: 0, value: 0 });
    force(x => x + 1);
    try {
      await fetch("/api/sync", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ col: "shipments", items: [fresh] }),
      });
    } catch (_) {}
    toast?.({ message: `Expédition "${fresh.name}" créée`, tone: "green" });
  };

  const deleteShipment = async (target) => {
    if (!target) return;
    if (!window.confirm(`Mettre l'expédition "${target.name || target.id}" à la corbeille ?`)) return;
    const idx = SHIPMENTS.findIndex(x => x.id === target.id);
    if (idx >= 0) SHIPMENTS.splice(idx, 1);
    await trashHook.send("shipments", target);
    force(x => x + 1);
    toast?.({ message: `Expédition → corbeille`, tone: "muted" });
  };

  const counts = {};
  SHIPMENT_STATUSES.forEach(s => {
    counts[s.id] = SHIPMENTS.filter(x => x.status === s.id).length;
  });

  const visible = tab === "all" ? SHIPMENTS : SHIPMENTS.filter(s => s.status === tab);
  const totalUnits = SHIPMENTS.reduce((a, b) => a + b.units, 0);
  const inTransitUnits = SHIPMENTS.filter(s => s.status === "en transit" || s.status === "douanes")
    .reduce((a, b) => a + b.units, 0);

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Expéditions FBA</div>
          <div className="page-sub">Canada → Amazon · suivi temps réel · {SHIPMENTS.length} envois actifs</div>
        </div>
        <button className="btn" data-variant="primary" onClick={() => setNewOpen(true)}>
          <Icon name="plus" size={13} /> Nouvelle expédition
        </button>
      </div>

      {/* KPI row */}
      <div className="grid" style={{ gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 14 }}>
        <div className="card" style={{ padding: 14 }}>
          <div style={{ fontSize: 10.5, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Total unités</div>
          <div className="mono" style={{ fontSize: 22, fontWeight: 600, marginTop: 4 }}>{totalUnits.toLocaleString()}</div>
          <div className="mono" style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 2 }}>4 expéditions actives</div>
        </div>
        <div className="card" style={{ padding: 14 }}>
          <div style={{ fontSize: 10.5, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: "0.06em" }}>En transit</div>
          <div className="mono" style={{ fontSize: 22, fontWeight: 600, marginTop: 4, color: "var(--blue)" }}>{inTransitUnits.toLocaleString()}</div>
          <div className="mono" style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 2 }}>{(inTransitUnits / totalUnits * 100).toFixed(0)}% du volume</div>
        </div>
        <div className="card" style={{ padding: 14 }}>
          <div style={{ fontSize: 10.5, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Aux douanes</div>
          <div className="mono" style={{ fontSize: 22, fontWeight: 600, marginTop: 4, color: "var(--amber)" }}>{counts["douanes"] || 0}</div>
          <div className="mono" style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 2 }}>Vérifier sous 48h</div>
        </div>
        <div className="card" style={{ padding: 14 }}>
          <div style={{ fontSize: 10.5, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: "0.06em" }}>ETA moyen</div>
          <div className="mono" style={{ fontSize: 22, fontWeight: 600, marginTop: 4 }}>15 mai</div>
          <div className="mono" style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 2 }}>+5j vs prévu</div>
        </div>
      </div>

      {/* Tabs */}
      <div className="row" style={{ gap: 6, marginBottom: 12, flexWrap: "wrap" }}>
        <button
          className="btn" data-variant={tab === "all" ? "primary" : "ghost"}
          onClick={() => setTab("all")}
        >
          Toutes · {SHIPMENTS.length}
        </button>
        {SHIPMENT_STATUSES.map(s => (
          <button
            key={s.id}
            className="btn" data-variant={tab === s.id ? "primary" : "ghost"}
            onClick={() => setTab(s.id)}
          >
            <Icon name={s.icon} size={12} /> {s.label} · {counts[s.id] || 0}
          </button>
        ))}
      </div>

      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <table className="table">
          <thead>
            <tr>
              <th>ID</th>
              <th>Trajet</th>
              <th>Unités</th>
              <th>Transporteur</th>
              <th>Statut</th>
              <th>ETA</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {visible.map(s => <ShipmentRow key={s.id} s={s} onSave={persistShipment} onDelete={deleteShipment} />)}
            {visible.length === 0 && (
              <tr><td colSpan={7} style={{ textAlign: "center", padding: 30, color: "var(--text-faint)" }}>
                Aucune expédition — clique « + Nouvelle expédition » pour en créer une.
              </td></tr>
            )}
          </tbody>
        </table>
      </div>

      {newOpen && (
        <div onClick={() => setNewOpen(false)} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.55)", zIndex: 9999, display: "grid", placeItems: "center" }}>
          <div className="card" onClick={(e) => e.stopPropagation()} style={{ width: 480, padding: 20 }}>
            <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 14 }}>Nouvelle expédition</div>
            <div className="stack" style={{ gap: 10 }}>
              <div>
                <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Nom *</div>
                <div className="input" style={{ height: 32, padding: "0 10px" }}>
                  <input autoFocus value={draft.name} onChange={(e) => setDraft(d => ({ ...d, name: e.target.value }))} placeholder="ex: Lot FBA mai" style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
                </div>
              </div>
              <div>
                <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Destination</div>
                <div className="input" style={{ height: 32, padding: "0 10px" }}>
                  <input value={draft.dest} onChange={(e) => setDraft(d => ({ ...d, dest: e.target.value }))} placeholder="ex: YYZ1 - Toronto" style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
                </div>
              </div>
              <div>
                <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Statut</div>
                <select value={draft.status} onChange={(e) => setDraft(d => ({ ...d, status: e.target.value }))} className="input" style={{ height: 32, width: "100%" }}>
                  {SHIPMENT_STATUSES.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
                </select>
              </div>
              <div>
                <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>ETA</div>
                <div className="input" style={{ height: 32, padding: "0 10px" }}>
                  <input value={draft.eta} onChange={(e) => setDraft(d => ({ ...d, eta: e.target.value }))} placeholder="ex: 22 mai" style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
                </div>
              </div>
              <div className="row" style={{ gap: 8 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Unités</div>
                  <div className="input" style={{ height: 32, padding: "0 10px" }}>
                    <input type="number" value={draft.units} onChange={(e) => setDraft(d => ({ ...d, units: e.target.value }))} style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
                  </div>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Valeur $</div>
                  <div className="input" style={{ height: 32, padding: "0 10px" }}>
                    <input type="number" value={draft.value} onChange={(e) => setDraft(d => ({ ...d, value: e.target.value }))} style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
                  </div>
                </div>
              </div>
            </div>
            <div className="row" style={{ marginTop: 16, justifyContent: "flex-end", gap: 8 }}>
              <button className="btn" onClick={() => setNewOpen(false)}>Annuler</button>
              <button className="btn" data-variant="primary" onClick={create} disabled={!draft.name.trim()}>Créer</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

window.Shipments = Shipments;
