// migrate.jsx - move existing policies into VaultCova for management
const { useState: useStateM, useEffect: useEffectM } = React;

const MIG_CATS = [
  { id: "vehicle", label: "Vehicle", icon: "car" },
  { id: "property", label: "Property", icon: "home" },
  { id: "equipment", label: "Equipment", icon: "cog" },
  { id: "inventory", label: "Stock", icon: "box" },
  { id: "jewelry", label: "Valuables", icon: "gem" },
  { id: "marine", label: "Cargo", icon: "ship" },
];

function MigrateWizard({ open, profile, onClose, onDone }) {
  const D = window.VC_DATA;
  const insurers = D.ADMIN_INSURERS.map((x) => x.name);
  const [step, setStep] = useStateM(0); // 0 details, 1 verifying, 2 confirm
  const [insurer, setInsurer] = useStateM(insurers[0]);
  const [polNo, setPolNo] = useStateM("");
  const [name, setName] = useStateM("");
  const [cat, setCat] = useStateM("vehicle");
  const [sum, setSum] = useStateM("");
  const [renews, setRenews] = useStateM("2027-02-01");

  useEffectM(() => { if (open) { setStep(0); setPolNo(""); setName(""); setSum(""); } }, [open]);

  const sumN = window.parseAmount(sum) || 0;
  const canVerify = polNo.trim().length >= 4 && name.trim().length >= 3 && sumN > 0;

  const verify = () => {
    setStep(1);
    setTimeout(() => setStep(2), 1800);
  };
  const finish = () => {
    onDone({
      id: D.nextId(), name: name.trim(), category: cat,
      purchase: Math.round(sumN * 0.9), replacement: sumN, sumInsured: sumN,
      status: "insured", bundle: null, insurer, premium: Math.round(sumN * 0.011 / 1000) * 1000,
      renews, note: "Migrated policy · " + polNo.trim().toUpperCase(),
    });
  };

  return (
    <window.Overlay open={open} onClose={step === 1 ? undefined : onClose} width={520}>
      {step === 0 && (
        <div>
          <div style={{ padding: "20px 24px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div>
              <h2 className="display" style={{ fontSize: 20 }}>Move a policy to VaultCova</h2>
              <p style={{ fontSize: 13, color: "var(--text-muted)", marginTop: 3 }}>Already insured? Keep your insurer - manage everything here.</p>
            </div>
            <button onClick={onClose} style={{ display: "grid", placeItems: "center", width: 34, height: 34, borderRadius: 999, background: "var(--surface-3)" }}><window.Icon name="close" size={17} /></button>
          </div>
          <div style={{ padding: 22, display: "grid", gap: 14 }}>
            <label>
              <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-muted)" }}>Current insurer</span>
              <div style={{ display: "flex", gap: 7, flexWrap: "wrap", marginTop: 7 }}>
                {insurers.map((n) => (
                  <button key={n} type="button" onClick={() => setInsurer(n)} style={{ padding: "8px 14px", borderRadius: 999, fontSize: 13, fontWeight: 700, background: insurer === n ? "var(--accent)" : "var(--surface-2)", color: insurer === n ? "#fff" : "var(--text-muted)", border: "1.5px solid " + (insurer === n ? "var(--accent)" : "var(--border)"), transition: "all .2s" }}>{n}</button>
                ))}
              </div>
            </label>
            <MigField label="Policy number" value={polNo} onChange={setPolNo} placeholder="e.g. LW-2025-88412" mono />
            <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 12 }}>
              <MigField label="What's insured?" value={name} onChange={setName} placeholder="e.g. Toyota Camry 2021" />
              <MigField label="Sum insured" value={sum} onChange={setSum} placeholder="e.g. ₦18M" mono />
            </div>
            <div>
              <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-muted)" }}>Category</span>
              <div style={{ display: "flex", gap: 7, flexWrap: "wrap", marginTop: 7 }}>
                {MIG_CATS.map((c) => (
                  <button key={c.id} type="button" onClick={() => setCat(c.id)} style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "8px 13px", borderRadius: 999, fontSize: 12.5, fontWeight: 700, background: cat === c.id ? "var(--accent-soft)" : "var(--surface-2)", color: cat === c.id ? "var(--accent-ink)" : "var(--text-muted)", border: "1.5px solid " + (cat === c.id ? "var(--accent)" : "var(--border)") }}><window.Icon name={c.icon} size={14} />{c.label}</button>
                ))}
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <MigField label="Renewal date" value={renews} onChange={setRenews} type="date" />
              <div>
                <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-muted)" }}>Policy document</span>
                <div style={{ display: "grid", placeItems: "center", marginTop: 7, padding: "11px 12px", borderRadius: 12, border: "1.5px dashed var(--border-strong)", color: "var(--text-faint)" }}>
                  <span className="mono" style={{ fontSize: 11.5 }}>[ drop PDF - optional ]</span>
                </div>
              </div>
            </div>
            <window.Btn size="lg" iconR="arrowR" disabled={!canVerify} style={{ width: "100%", justifyContent: "center", marginTop: 4 }} onClick={verify}>Verify with {insurer}</window.Btn>
            <p style={{ textAlign: "center", fontSize: 11.5, color: "var(--text-faint)", margin: 0 }}>Your cover stays exactly as-is - VaultCova adds tracking, renewals, claims and rewards on top.</p>
          </div>
        </div>
      )}

      {step === 1 && (
        <div style={{ padding: 48, textAlign: "center" }}>
          <span style={{ display: "inline-block", width: 52, height: 52, border: "4px solid var(--surface-3)", borderTopColor: "var(--accent)", borderRadius: 999, animation: "vc-spin .8s linear infinite" }} />
          <h2 className="display" style={{ fontSize: 21, marginTop: 22 }}>Verifying with {insurer}…</h2>
          <p style={{ fontSize: 14, color: "var(--text-muted)", marginTop: 6 }}>Confirming policy {polNo.toUpperCase()} and its cover details.</p>
        </div>
      )}

      {step === 2 && (
        <div style={{ padding: 32, textAlign: "center" }}>
          <span style={{ display: "grid", placeItems: "center", width: 72, height: 72, borderRadius: 999, background: "var(--success)", color: "#fff", margin: "0 auto", animation: "vc-scale-in .4s var(--ease) both" }}><window.Icon name="check" size={40} stroke={3} /></span>
          <h2 className="display" style={{ fontSize: 23, marginTop: 18 }}>Policy verified</h2>
          <p style={{ fontSize: 14.5, color: "var(--text-muted)", marginTop: 8 }}><b>{name}</b> · {insurer} · {window.VC_DATA.fmtFull(sumN)} cover</p>
          <div style={{ margin: "18px 0", padding: 14, borderRadius: 14, background: "var(--accent-soft)", border: "1px solid var(--accent)", textAlign: "left", display: "grid", gap: 8 }}>
            {["Renewal reminders & lapse protection", "Claims filed & tracked from here", "Counts toward VaultRewards cashback", "Included in your coverage gap analysis"].map((f) => (
              <div key={f} style={{ display: "flex", gap: 8, alignItems: "center", fontSize: 13, color: "var(--accent-ink)", fontWeight: 600 }}>
                <window.Icon name="check" size={14} stroke={3} />{f}
              </div>
            ))}
          </div>
          <window.Btn size="lg" iconR="arrowR" style={{ width: "100%", justifyContent: "center" }} onClick={finish}>Add to my VaultLog</window.Btn>
        </div>
      )}
    </window.Overlay>
  );
}

function MigField({ label, value, onChange, placeholder, type = "text", mono }) {
  return (
    <label style={{ display: "block" }}>
      <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-muted)" }}>{label}</span>
      <input type={type} value={value} placeholder={placeholder} onChange={(e) => onChange(e.target.value)}
        className={mono ? "mono" : ""}
        style={{ width: "100%", marginTop: 7, padding: "12px 13px", borderRadius: 12, border: "1.5px solid var(--border)", background: "var(--surface-2)", fontSize: 14.5, color: "var(--text)", outline: "none", fontFamily: mono ? "var(--font-mono)" : "var(--font-body)" }} />
    </label>
  );
}

Object.assign(window, { MigrateWizard });
