/* GUIDKO Assurance — branche à la demande, reliée à KYC + Wallet + trajets/véhicules.
   Couvre : conduite (élève/accompagnée), trajets covoit, missions livraison, véhicules
   (vente/location P2P), responsabilité pro. Activation/désactivation, paiement via Wallet. */

const INSURANCE_PLANS = [
  { k: "trajet", g: "shield", color: "#0FB76B", fr: "Assurance Trajet", en: "Trip insurance",
    price: 0, unit: { fr: "Incluse dès KYC vérifié", en: "Included once KYC verified" },
    cover: { fr: "Chaque covoiturage et livraison couvert : dommages, responsabilité civile, assistance.", en: "Every carpool & delivery covered: damage, liability, assistance." }, on: true, badge: { fr: "Incluse", en: "Included" } },
  { k: "conduite", g: "eleve", color: "#FF5A1F", fr: "Conduite & Apprentissage", en: "Driving & Learning",
    price: 6, unit: { fr: "/ mois", en: "/ mo" },
    cover: { fr: "Élève et conduite accompagnée : véhicule auto-école, double-commande, accident pendant la leçon.", en: "Student & supervised driving: school vehicle, dual-control, in-lesson accident." }, on: false },
  { k: "vehicule", g: "auto", color: "#A78BFA", fr: "Véhicule à la demande", en: "On-demand vehicle",
    price: 0, unit: { fr: "Par jour de location", en: "Per rental day" },
    cover: { fr: "Location P2P : caution couverte, tous risques le temps de la location, constat numérique.", en: "P2P rental: deposit covered, all-risk during rental, digital report." }, on: false, badge: { fr: "À l'usage", en: "Pay-per-use" } },
  { k: "pro", g: "target", color: "#3B6FF8", fr: "Responsabilité Pro", en: "Pro liability",
    price: 19, unit: { fr: "/ mois", en: "/ mo" },
    cover: { fr: "Moniteurs & auto-écoles : RC professionnelle, flotte, protection juridique.", en: "Instructors & schools: pro liability, fleet, legal protection." }, on: false },
];

const CLAIMS_SEED = [
  { id: "cl1", ref: "SIN-2026-0412", type: { fr: "Trajet covoit", en: "Carpool trip" }, date: "08/06/2026", amount: 240, status: "paid" },
  { id: "cl2", ref: "SIN-2026-0455", type: { fr: "Rayure location", en: "Rental scratch" }, date: "12/06/2026", amount: 180, status: "review" },
];

function AssurancePage({ role, navigate }) {
  const C = GK.colors;
  const { t, lang } = useI18n();
  const toast = useToast();
  const money = (v) => window.GKmoney ? window.GKmoney(v) : v + " €";
  const [view, setView] = React.useState("landing"); // landing | app
  const [side, setSide] = React.useState("particulier");
  const [plans, setPlans] = React.useState(() => Object.fromEntries(INSURANCE_PLANS.map(p => [p.k, p.on])));
  const [claimOpen, setClaimOpen] = React.useState(false);
  const active = INSURANCE_PLANS.filter(p => plans[p.k]);
  const monthly = INSURANCE_PLANS.filter(p => plans[p.k] && p.price > 0 && (p.unit.fr.includes("mois"))).reduce((s, p) => s + p.price, 0);

  function toggle(k) {
    setPlans(s => ({ ...s, [k]: !s[k] }));
    toast.push(!plans[k] ? t("Couverture activée — prélevée via Wallet.", "Coverage on — billed via Wallet.") : t("Couverture désactivée.", "Coverage off."), !plans[k] ? "signal" : "neutral");
  }

  // ===== PORTE D'ENTRÉE : GUIDKO Assurance comme app distincte =====
  if (view === "landing") {
    const door = (opts) => (
      <div onClick={opts.onClick} style={{ flex: 1, display: "flex", alignItems: "center", gap: 16, padding: "22px 24px", borderRadius: 16, cursor: "pointer", background: opts.dark ? C.ink : "#fff", color: opts.dark ? "#fff" : C.ink, border: `1px solid ${opts.dark ? C.ink : C.softLine}`, transition: "transform .14s, box-shadow .14s" }}
        onMouseEnter={e => { e.currentTarget.style.transform = "translateY(-3px)"; e.currentTarget.style.boxShadow = "0 18px 44px rgba(11,15,31,.12)"; }}
        onMouseLeave={e => { e.currentTarget.style.transform = "none"; e.currentTarget.style.boxShadow = "none"; }}>
        <div style={{ width: 52, height: 52, borderRadius: 14, background: opts.dark ? `${C.flame}22` : C.cream, color: opts.dark ? C.flame : C.ink, display: "grid", placeItems: "center", flexShrink: 0 }}>{window.GKIcon ? <GKIcon name={opts.icon} size={24} /> : "◆"}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <span style={{ display: "inline-block", fontFamily: "'Geist Mono', monospace", fontSize: 9.5, letterSpacing: "0.14em", color: opts.dark ? C.flame : C.sky, marginBottom: 5 }}>{opts.tag}</span>
          <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 24, fontWeight: 400, lineHeight: 1, marginBottom: 6 }}>{opts.title}</div>
          <p style={{ fontSize: 12.5, color: opts.dark ? "#9098B5" : C.slate, lineHeight: 1.45 }}>{opts.desc}</p>
        </div>
        <span style={{ color: opts.dark ? C.flame : C.slate, fontSize: 20, flexShrink: 0 }}>→</span>
      </div>
    );
    return (
      <div className="gk-scroll" style={{ height: "100%", overflowY: "auto", display: "grid", gridTemplateColumns: "1fr 1fr", background: C.paper }}>
        {/* Présentation (gauche) */}
        <div style={{ background: C.ink, color: "#fff", padding: "44px 40px", display: "flex", flexDirection: "column", justifyContent: "center", position: "relative", overflow: "hidden" }}>
          <svg style={{ position: "absolute", right: -90, bottom: -40, opacity: 0.06 }} width="320" height="320" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="0.4"><path d="M12 3l7 2.5V11c0 4.5-3 8-7 9.5-4-1.5-7-5-7-9.5V5.5L12 3Z"/></svg>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 10, marginBottom: 22 }}>
            <div style={{ width: 38, height: 38, borderRadius: 11, background: C.signal, display: "grid", placeItems: "center" }}>{window.GKIcon ? <GKIcon name="shield" size={19} /> : "🛡"}</div>
            <span style={{ fontWeight: 800, letterSpacing: "0.04em" }}>GUIDKO</span>
            <span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 9, color: C.signal, letterSpacing: "0.18em", paddingLeft: 10, borderLeft: "1px solid #1F2542" }}>ASSURANCE</span>
          </div>
          <h1 style={{ fontFamily: "'Instrument Serif', serif", fontSize: 44, fontWeight: 400, lineHeight: 1.02, letterSpacing: "-0.025em", margin: "0 0 16px" }}>
            {t("L'assurance qui suit", "Insurance that follows")} <span style={{ fontStyle: "italic", color: C.flame }}>{t("ta mobilité.", "your mobility.")}</span>
          </h1>
          <p style={{ fontSize: 15, color: "#C9CEE3", lineHeight: 1.55, maxWidth: 380 }}>
            {t("Une branche à part entière, reliée à GUIDKO : trajet, conduite, véhicule, flotte. Gérée en interne, ou souscrite comme client externe.", "A standalone branch, linked to GUIDKO: trip, driving, vehicle, fleet. Managed internally, or subscribed as an external client.")}
          </p>
          <div style={{ display: "flex", gap: 26, marginTop: 30 }}>
            {[["4", t("COUVERTURES", "COVERS")], ["100%", t("VIA WALLET", "VIA WALLET")], ["24/7", t("LIA SINISTRES", "LIA CLAIMS")]].map(([v, l]) => (
              <div key={l}><div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 26, lineHeight: 1 }}>{v}</div><div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 8, color: "#7A82A8", letterSpacing: "0.14em", marginTop: 5 }}>{l}</div></div>
            ))}
          </div>
        </div>
        {/* Deux portes (droite, empilées et centrées) */}
        <div style={{ padding: "44px 40px", display: "flex", flexDirection: "column", justifyContent: "center", gap: 16 }}>
          <div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 10, letterSpacing: "0.16em", color: C.slate, marginBottom: 2 }}>{t("CHOISIS TON ENTRÉE", "CHOOSE YOUR ENTRY")}</div>
          {door({ onClick: () => { setSide("particulier"); setView("app"); }, icon: "eleve", tag: "PARTICULIER", title: t("Je m'assure", "I get covered"), desc: t("Couverture à la demande : trajets, conduite, véhicules. Activation en un clic.", "On-demand cover: trips, driving, vehicles. One-click activation.") })}
          {door({ onClick: () => { setSide("pro"); setView("app"); }, dark: true, icon: "b2b", tag: "PRO · FLOTTE", title: t("J'assure mon activité", "I insure my business"), desc: t("Responsabilité pro, flotte, moniteurs et auto-écoles. Gestion centralisée.", "Pro liability, fleet, instructors and schools. Centralized management.") })}
          <div style={{ marginTop: 6, padding: 13, background: "#FBF8EE", borderRadius: 10, borderLeft: `3px solid ${C.flame}`, fontSize: 12, color: C.slate, lineHeight: 1.5 }}>
            {t("Ton KYC vérifié débloque l'assurance trajet incluse. Tout est relié à ton Wallet GUIDKO.", "Your verified KYC unlocks the included trip insurance. Everything links to your GUIDKO Wallet.")}
          </div>
        </div>
      </div>
    );
  }

  return (
    <>
      <Topbar subtitle={side === "pro" ? t("ASSURANCE · PRO & FLOTTE", "INSURANCE · PRO & FLEET") : t("ASSURANCE · PARTICULIER", "INSURANCE · PERSONAL")} title={t("Mes couvertures", "My coverage")} search={false}
        actions={<><Button kind="ghost" size="sm" onClick={() => setView("landing")}>{t("Changer d'entrée", "Switch entry")}</Button><Button kind="primary" onClick={() => setClaimOpen(true)}>{t("Déclarer un sinistre", "File a claim")}</Button></>}/>
      <PageBody>
        {/* Hero */}
        <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 14, marginBottom: 16 }}>
          <Card dark style={{ padding: 26, position: "relative", overflow: "hidden" }}>
            <Label color="#7A82A8">{t("PROTECTION ACTIVE", "ACTIVE PROTECTION")}</Label>
            <div style={{ display: "flex", alignItems: "center", gap: 16, margin: "14px 0 8px" }}>
              <div style={{ width: 60, height: 60, borderRadius: 16, background: C.signal, display: "grid", placeItems: "center", color: "#fff" }}>{window.GKIcon ? <GKIcon name="shield" size={28}/> : "🛡"}</div>
              <div>
                <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 32, lineHeight: 1 }}>{active.length} {t("couvertures", "covers")}</div>
                <div style={{ fontSize: 13, color: "#9098B5", marginTop: 4 }}>{monthly > 0 ? money(monthly) + t(" / mois", " / mo") : t("Sans surcoût mensuel", "No monthly cost")}</div>
              </div>
            </div>
            <div style={{ marginTop: 14, padding: 13, background: "#1F2542", borderRadius: 10, borderLeft: `3px solid ${C.flame}`, fontSize: 12.5, color: "#C9CEE3", lineHeight: 1.5 }}>
              {t("Ton identité KYC vérifiée débloque l'assurance trajet incluse. Tout est prélevé et indemnisé via ton Wallet.", "Your verified KYC unlocks the included trip insurance. Everything is billed and paid out via your Wallet.")}
            </div>
          </Card>
          <Card style={{ padding: 0, overflow: "hidden" }}>
            <div style={{ padding: "14px 18px", borderBottom: `1px solid ${C.softLine}`, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <Label>{t("SINISTRES", "CLAIMS")}</Label>
              <Pill tone="signal">{CLAIMS_SEED.filter(c => c.status === "paid").length} {t("indemnisés", "paid")}</Pill>
            </div>
            {CLAIMS_SEED.map((c, i) => (
              <div key={c.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 18px", borderTop: i === 0 ? "none" : `1px solid ${C.softLine}` }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600 }}>{c.type[lang] || c.type.fr}</div>
                  <div style={{ fontSize: 11, color: C.slate, fontFamily: "'Geist Mono', monospace" }}>{c.ref} · {c.date}</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 13, fontWeight: 600 }}>{money(c.amount)}</div>
                  <Pill tone={c.status === "paid" ? "signal" : "flame"}>{c.status === "paid" ? t("Indemnisé", "Paid") : t("En cours", "Review")}</Pill>
                </div>
              </div>
            ))}
          </Card>
        </div>

        {/* Plans */}
        <Label style={{ marginBottom: 12 }}>{t("COUVERTURES DISPONIBLES — ACTIVE À LA DEMANDE", "AVAILABLE COVERAGE — ACTIVATE ON DEMAND")}</Label>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 14 }}>
          {INSURANCE_PLANS.map(p => {
            const on = plans[p.k];
            return (
              <Card key={p.k} style={{ padding: 20, border: on ? `2px solid ${p.color}` : `1px solid ${C.softLine}` }}>
                <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
                  <div style={{ width: 42, height: 42, borderRadius: 11, background: p.color + "22", color: p.color, display: "grid", placeItems: "center" }}>{window.GKIcon && window.hasGKIcon && window.hasGKIcon(p.g) ? <GKIcon name={p.g} size={20}/> : "🛡"}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 15.5, fontWeight: 600 }}>{p[lang] || p.fr}</div>
                    {p.badge && <span style={{ fontSize: 10.5, color: p.color, fontWeight: 600 }}>{p.badge[lang] || p.badge.fr}</span>}
                  </div>
                </div>
                <p style={{ fontSize: 13, color: C.slate, lineHeight: 1.5, minHeight: 56 }}>{p.cover[lang] || p.cover.fr}</p>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 14, paddingTop: 14, borderTop: `1px solid ${C.softLine}` }}>
                  <div>
                    <span style={{ fontFamily: "'Instrument Serif', serif", fontSize: 24 }}>{p.price === 0 ? (p.k === "trajet" ? t("Inclus", "Free") : money(0)) : money(p.price)}</span>
                    <span style={{ fontSize: 12, color: C.slate }}> {p.unit[lang] || p.unit.fr}</span>
                  </div>
                  {p.k === "trajet"
                    ? <Pill tone="signal">{t("Active ✓", "On ✓")}</Pill>
                    : <Button size="sm" kind={on ? "light" : "primary"} onClick={() => toggle(p.k)}>{on ? t("Désactiver", "Turn off") : t("Activer", "Activate")}</Button>}
                </div>
              </Card>
            );
          })}
        </div>

        {/* Cross-links */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 16 }}>
          <Card style={{ padding: 16, background: "#FBF8EE", display: "flex", gap: 12, alignItems: "center" }}>
            <span style={{ width: 32, height: 32, borderRadius: 8, background: "#fff", border: `1px solid ${C.softLine}`, display: "grid", placeItems: "center", color: C.ink }}>{window.GKIcon ? <GKIcon name="trust" size={17}/> : "🛡"}</span>
            <div style={{ flex: 1, fontSize: 12.5, color: C.slate }}>{t("Vérifie ton KYC pour débloquer l'assurance incluse.", "Verify your KYC to unlock included insurance.")}</div>
            {navigate && <Button size="sm" kind="ink" onClick={() => navigate(`/${role}/trust`)}>{t("Confiance", "Trust")} →</Button>}
          </Card>
          <Card style={{ padding: 16, display: "flex", gap: 12, alignItems: "center" }}>
            <span style={{ width: 32, height: 32, borderRadius: 8, background: C.cream, display: "grid", placeItems: "center", color: C.ink }}>{window.GKIcon ? <GKIcon name="wallet" size={17}/> : "▣"}</span>
            <div style={{ flex: 1, fontSize: 12.5, color: C.slate }}>{t("Cotisations et indemnisations passent par ton Wallet.", "Premiums and payouts go through your Wallet.")}</div>
            {navigate && <Button size="sm" kind="ghost" onClick={() => navigate(`/${role}/wallet`)}>{t("Wallet", "Wallet")} →</Button>}
          </Card>
        </div>
      </PageBody>

      {/* Claim modal */}
      {claimOpen && (
        <div onClick={() => setClaimOpen(false)} style={{ position: "fixed", inset: 0, background: "rgba(8,11,24,0.6)", zIndex: 9400, display: "grid", placeItems: "center", padding: 20, backdropFilter: "blur(3px)" }}>
          <div onClick={e => e.stopPropagation()} style={{ background: "#fff", borderRadius: 18, padding: 28, width: 460, maxWidth: "100%", boxShadow: "0 30px 80px rgba(0,0,0,0.4)" }}>
            <div style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "5px 11px", borderRadius: 999, background: "#FFF1EB", color: C.flame, fontSize: 11.5, fontWeight: 600, marginBottom: 14 }}>{t("DÉCLARATION DE SINISTRE", "CLAIM FILING")}</div>
            <h3 style={{ fontFamily: "'Instrument Serif', serif", fontSize: 28, fontWeight: 400, margin: "0 0 6px" }}>{t("Que s'est-il passé ?", "What happened?")}</h3>
            <p style={{ fontSize: 13, color: C.slate, marginBottom: 16, lineHeight: 1.5 }}>{t("Lia pré-analyse ta déclaration et accélère l'indemnisation via le Wallet.", "Lia pre-analyzes your claim and speeds up the Wallet payout.")}</p>
            <Input label={t("Type d'incident", "Incident type")} value={t("Accrochage covoiturage", "Carpool fender-bender")} onChange={() => {}}/>
            <Input label={t("Description", "Description")} value="" onChange={() => {}} placeholder={t("Décris en quelques mots…", "Describe in a few words…")}/>
            <div style={{ display: "flex", gap: 10, marginTop: 12 }}>
              <Button kind="ghost" full onClick={() => setClaimOpen(false)}>{t("Annuler", "Cancel")}</Button>
              <Button kind="primary" full onClick={() => { setClaimOpen(false); toast.push(t("Sinistre déclaré — Lia traite ton dossier.", "Claim filed — Lia is processing it."), "signal"); }}>{t("Envoyer", "Submit")} →</Button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

window.AssurancePage = AssurancePage;
