/* GUIDKO Contrats & signature électronique.
   Modèles : inscription élève, location P2P, cession véhicule, contrat livreur,
   affiliation moniteur↔école. Signature au doigt (canvas) + step-up sécurité.
   Persisté en localStorage (guidko_contracts). Role-aware. */

const CONTRACT_TEMPLATES = [
  { k: "eleve",   roles: ["eleve"], g: "▲", color: "#FF5A1F", fr: "Inscription élève", en: "Student enrollment", party: { fr: "Élève ↔ Auto-école", en: "Student ↔ School" },
    body: { fr: "Le présent contrat lie l'élève à l'auto-école pour la formation au permis B. Forfait 20 h, code illimité, 2 examens blancs. Mensualité 89 €. Résiliation à 30 jours.", en: "This contract binds the student to the school for category B training. 20h package, unlimited code, 2 mock exams. €89/month. 30-day termination." } },
  { k: "location",roles: ["gerant","moniteur","auto","covoit","eleve","livraison"], g: "🔑", color: "#A78BFA", fr: "Location entre particuliers", en: "Peer-to-peer rental", party: { fr: "Propriétaire ↔ Locataire", en: "Owner ↔ Renter" },
    body: { fr: "Location d'un véhicule entre particuliers via GUIDKO. Caution bloquée en escrow Wallet. Assurance trajet GUIDKO incluse. État des lieux photo à la remise et au retour.", en: "Peer-to-peer vehicle rental via GUIDKO. Deposit held in Wallet escrow. GUIDKO trip insurance included. Photo condition report at handover and return." } },
  { k: "cession", roles: ["gerant","moniteur","auto","covoit","eleve","livraison"], g: "⇄", color: "#3B6FF8", fr: "Cession de véhicule", en: "Vehicle sale", party: { fr: "Vendeur ↔ Acheteur", en: "Seller ↔ Buyer" },
    body: { fr: "Acte de cession d'un véhicule. Paiement sécurisé par escrow : les fonds sont libérés au vendeur à la remise confirmée. Certificat de cession et carte grise générés automatiquement.", en: "Vehicle sale deed. Escrow-secured payment: funds released to seller upon confirmed handover. Transfer certificate and registration auto-generated." } },
  { k: "livreur", roles: ["livraison"], g: "📦", color: "#0FB76B", fr: "Contrat livreur", en: "Courier contract", party: { fr: "Livreur ↔ GUIDKO", en: "Courier ↔ GUIDKO" },
    body: { fr: "Contrat de prestation de livraison indépendante. Commission 12% (6% en Pro). Paiement via Wallet. Assurance pendant les missions. Pas de lien de subordination.", en: "Independent delivery service contract. 12% commission (6% Pro). Payment via Wallet. Insurance during missions. No subordination." } },
  { k: "moniteur",roles: ["gerant","moniteur"], g: "♛", color: "#0B0F1F", fr: "Affiliation moniteur", en: "Instructor affiliation", party: { fr: "Moniteur ↔ Auto-école", en: "Instructor ↔ School" },
    body: { fr: "Affiliation d'un moniteur indépendant à une auto-école. Commission reversée à l'école 15%. Le moniteur conserve son espace privé et ses autres affiliations.", en: "Independent instructor affiliated to a school. 15% fee to the school. The instructor keeps their private space and other affiliations." } },
];

const SIGNED_SEED = [
  { id: "sg1", tpl: "eleve",   title: "Inscription · Léa Mercier", other: "Auto-École Lubasa", date: "12/03/2026", status: "signed" },
  { id: "sg2", tpl: "cession", title: "Vente Peugeot 208", other: "AutoPlus 93", date: "—", status: "pending" },
];

function loadContracts() { try { return JSON.parse(localStorage.getItem("guidko_contracts") || "null") || SIGNED_SEED; } catch (e) { return SIGNED_SEED; } }
function saveContracts(list) { try { localStorage.setItem("guidko_contracts", JSON.stringify(list)); } catch (e) {} }

// --- Canvas de signature au doigt ---
function SignaturePad({ onChange }) {
  const ref = React.useRef(null);
  const drawing = React.useRef(false);
  const has = React.useRef(false);
  React.useEffect(() => {
    const cv = ref.current; if (!cv) return;
    const ctx = cv.getContext("2d");
    const rect = cv.getBoundingClientRect();
    cv.width = rect.width * 2; cv.height = rect.height * 2; ctx.scale(2, 2);
    ctx.strokeStyle = "#0B0F1F"; ctx.lineWidth = 2.2; ctx.lineCap = "round"; ctx.lineJoin = "round";
    const pos = (e) => { const r = cv.getBoundingClientRect(); const p = e.touches ? e.touches[0] : e; return { x: p.clientX - r.left, y: p.clientY - r.top }; };
    const start = (e) => { drawing.current = true; const { x, y } = pos(e); ctx.beginPath(); ctx.moveTo(x, y); e.preventDefault(); };
    const move = (e) => { if (!drawing.current) return; const { x, y } = pos(e); ctx.lineTo(x, y); ctx.stroke(); has.current = true; e.preventDefault(); };
    const end = () => { if (drawing.current && has.current && onChange) onChange(true); drawing.current = false; };
    cv.addEventListener("mousedown", start); cv.addEventListener("mousemove", move); window.addEventListener("mouseup", end);
    cv.addEventListener("touchstart", start, { passive: false }); cv.addEventListener("touchmove", move, { passive: false }); window.addEventListener("touchend", end);
    cv._clear = () => { ctx.clearRect(0, 0, cv.width, cv.height); has.current = false; if (onChange) onChange(false); };
    return () => { cv.removeEventListener("mousedown", start); cv.removeEventListener("mousemove", move); window.removeEventListener("mouseup", end); cv.removeEventListener("touchstart", start); cv.removeEventListener("touchmove", move); window.removeEventListener("touchend", end); };
  }, []);
  return (
    <div style={{ position: "relative" }}>
      <canvas ref={ref} style={{ width: "100%", height: 150, background: "#fff", border: "1px dashed #C9C2AE", borderRadius: 10, touchAction: "none", cursor: "crosshair", display: "block" }}/>
      <button onClick={() => ref.current && ref.current._clear()} style={{ position: "absolute", top: 8, right: 8, padding: "4px 10px", borderRadius: 7, border: "1px solid #E3DCC9", background: "#F5F0E6", fontSize: 11, cursor: "pointer", fontFamily: "inherit", color: "#6B7280" }}>↺ Effacer</button>
    </div>
  );
}

function ContractsPage({ role, navigate }) {
  const C = GK.colors;
  const { t, lang } = useI18n();
  const toast = useToast();
  const [list, setList] = React.useState(loadContracts());
  const [view, setView] = React.useState(null);   // template object being signed
  const [signed, setSigned] = React.useState(false);
  const [hasSig, setHasSig] = React.useState(false);
  const [stepup, setStepup] = React.useState(false);
  const tplOf = (k) => CONTRACT_TEMPLATES.find(x => x.k === k);
  // Accès aligné au profil : on ne propose que les modèles pertinents pour ce rôle.
  const myTemplates = CONTRACT_TEMPLATES.filter(tpl => !tpl.roles || tpl.roles.includes(role));
  // Documents liés à un véhicule (situationnels) vs documents du rôle.
  const VEHICLE_KINDS = ["location", "cession"];
  const coreTpls = myTemplates.filter(tpl => !VEHICLE_KINDS.includes(tpl.k));
  const vehicleTpls = myTemplates.filter(tpl => VEHICLE_KINDS.includes(tpl.k));

  function finalize() {
    const entry = { id: "sg" + Date.now(), tpl: view.k, title: (view[lang] || view.fr), other: "GUIDKO", date: new Date().toLocaleDateString("fr-FR"), status: "signed" };
    const next = [entry, ...list]; setList(next); saveContracts(next);
    setSigned(true);
  }

  // --- Vue signature d'un modèle ---
  if (view) {
    return (
      <>
        {typeof StepUp !== "undefined" && <StepUp open={stepup} reason={t("Signature d'un document juridique","Signing a legal document")} onCancel={() => setStepup(false)} onConfirm={() => { setStepup(false); finalize(); }}/>}
        <Topbar subtitle={t("CONTRAT","CONTRACT")} title={view[lang] || view.fr} search={false}
          actions={<Button kind="ghost" size="sm" onClick={() => { setView(null); setSigned(false); setHasSig(false); }}>← {t("Tous les contrats","All contracts")}</Button>}/>
        <PageBody>
          <div style={{ maxWidth: 680, margin: "0 auto" }}>
            {signed ? (
              <Card style={{ padding: 40, textAlign: "center" }}>
                <div style={{ width: 70, height: 70, borderRadius: 20, background: C.signal, color: "#fff", display: "grid", placeItems: "center", fontSize: 32, margin: "0 auto 18px" }}>✓</div>
                <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 36, lineHeight: 1 }}>{t("Document signé","Document signed")}</div>
                <p style={{ fontSize: 14, color: C.slate, margin: "12px 0 8px", lineHeight: 1.5 }}>{t("Signature électronique horodatée et certifiée. Une copie PDF est dans ton Wallet et envoyée par email.","Time-stamped, certified e-signature. A PDF copy is in your Wallet and emailed to you.")}</p>
                <div style={{ display: "inline-flex", gap: 8, alignItems: "center", fontFamily: "'Geist Mono', monospace", fontSize: 11, color: C.slate, padding: "8px 14px", background: C.paper, borderRadius: 8, marginTop: 8 }}>
                  🔏 SHA-256 · {Date.now().toString(16).slice(-10).toUpperCase()}
                </div>
                <div style={{ display: "flex", gap: 10, justifyContent: "center", marginTop: 22 }}>
                  <Button kind="light" onClick={() => toast.push(t("PDF téléchargé","PDF downloaded"), "signal")}>↓ {t("Télécharger le PDF","Download PDF")}</Button>
                  <Button kind="primary" onClick={() => { setView(null); setSigned(false); setHasSig(false); }}>{t("Terminé","Done")}</Button>
                </div>
              </Card>
            ) : (
              <>
                {/* Document */}
                <Card style={{ padding: 0, overflow: "hidden", marginBottom: 16 }}>
                  <div style={{ padding: "20px 26px", borderBottom: `1px solid ${C.softLine}`, display: "flex", alignItems: "center", gap: 14 }}>
                    <div style={{ width: 44, height: 44, borderRadius: 11, background: view.color === "#0B0F1F" ? C.ink : view.color + "22", color: view.color === "#0B0F1F" ? C.flame : view.color, display: "grid", placeItems: "center", fontSize: 20 }}>{view.g}</div>
                    <div>
                      <div style={{ fontSize: 17, fontWeight: 700 }}>{view[lang] || view.fr}</div>
                      <div style={{ fontSize: 12.5, color: C.slate }}>{view.party[lang] || view.party.fr}</div>
                    </div>
                    <span style={{ marginLeft: "auto", fontFamily: "'Geist Mono', monospace", fontSize: 10, color: C.slate }}>RÉF · {view.k.toUpperCase()}-2026</span>
                  </div>
                  <div style={{ padding: "24px 26px", fontSize: 14, lineHeight: 1.7, color: C.ink }}>
                    <p style={{ marginBottom: 14 }}>{view.body[lang] || view.body.fr}</p>
                    <div style={{ display: "flex", flexDirection: "column", gap: 9, padding: "16px 0", borderTop: `1px solid ${C.softLine}` }}>
                      {[t("Conforme au droit en vigueur dans ton pays.","Compliant with your country's law."), t("Litiges arbitrés par l'Admin GUIDKO (escrow protégé).","Disputes arbitrated by GUIDKO Admin (escrow protected)."), t("Données chiffrées · RGPD.","Encrypted data · GDPR.")].map((l, i) => (
                        <div key={i} style={{ display: "flex", gap: 9, fontSize: 13, color: C.slate }}><span style={{ color: C.signal }}>✓</span>{l}</div>
                      ))}
                    </div>
                  </div>
                </Card>

                {/* Signature */}
                <Card style={{ padding: 22 }}>
                  <Label style={{ marginBottom: 4 }}>{t("SIGNATURE ÉLECTRONIQUE","E-SIGNATURE")}</Label>
                  <p style={{ fontSize: 12.5, color: C.slate, margin: "0 0 14px" }}>{t("Signe avec ton doigt ou ta souris dans le cadre.","Sign with your finger or mouse in the box.")}</p>
                  <SignaturePad onChange={setHasSig}/>
                  <label style={{ display: "flex", gap: 10, alignItems: "flex-start", margin: "16px 0 4px", fontSize: 12.5, color: C.slate, lineHeight: 1.45, cursor: "pointer" }}>
                    <input type="checkbox" defaultChecked style={{ marginTop: 2, accentColor: C.flame }}/>
                    {t("J'ai lu et j'accepte les termes. Cette signature a valeur d'engagement légal.","I have read and accept the terms. This signature is legally binding.")}
                  </label>
                  <Button kind="flame" size="lg" full style={{ marginTop: 16, opacity: hasSig ? 1 : 0.45 }} onClick={() => hasSig && setStepup(true)}>🔏 {t("Signer le document","Sign the document")}</Button>
                </Card>
              </>
            )}
          </div>
        </PageBody>
      </>
    );
  }

  // --- Liste + modèles ---
  return (
    <>
      <Topbar subtitle={t("CONTRATS & SIGNATURE","CONTRACTS & SIGNATURE")} title={t("Mes documents","My documents")} search={false}/>
      <PageBody>
        {/* New from template */}
        {coreTpls.length > 0 && <Label style={{ marginBottom: 12 }}>{t("TES DOCUMENTS","YOUR DOCUMENTS")}</Label>}
        {coreTpls.length > 0 && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 12, marginBottom: 26 }}>
          {coreTpls.map(tpl => (
            <Card key={tpl.k} hover onClick={() => { setView(tpl); setSigned(false); setHasSig(false); }} style={{ padding: 18 }}>
              <div style={{ width: 40, height: 40, borderRadius: 11, background: tpl.color === "#0B0F1F" ? C.ink : tpl.color + "22", color: tpl.color === "#0B0F1F" ? C.flame : tpl.color, display: "grid", placeItems: "center", fontSize: 18, marginBottom: 12 }}>{tpl.g}</div>
              <div style={{ fontSize: 14.5, fontWeight: 600 }}>{tpl[lang] || tpl.fr}</div>
              <div style={{ fontSize: 12, color: C.slate, marginTop: 3 }}>{tpl.party[lang] || tpl.party.fr}</div>
              <div style={{ marginTop: 12, display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12, color: tpl.color === "#0B0F1F" ? C.flame : tpl.color, fontWeight: 600 }}>{t("Rédiger & signer","Draft & sign")} →</div>
            </Card>
          ))}
        </div>
        )}

        {/* Documents liés à un véhicule — situationnels (seulement si tu vends/loues) */}
        {vehicleTpls.length > 0 && (
          <>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
              <Label>{t("SI TU VENDS OU LOUES UN VÉHICULE","IF YOU SELL OR RENT A VEHICLE")}</Label>
              <span style={{ height: 1, background: C.softLine, flex: 1 }}></span>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 12, marginBottom: 26 }}>
              {vehicleTpls.map(tpl => (
                <Card key={tpl.k} hover onClick={() => { setView(tpl); setSigned(false); setHasSig(false); }} style={{ padding: 18, background: "#FBF8EE" }}>
                  <div style={{ width: 40, height: 40, borderRadius: 11, background: tpl.color + "22", color: tpl.color, display: "grid", placeItems: "center", fontSize: 18, marginBottom: 12 }}>{tpl.g}</div>
                  <div style={{ fontSize: 14.5, fontWeight: 600 }}>{tpl[lang] || tpl.fr}</div>
                  <div style={{ fontSize: 12, color: C.slate, marginTop: 3 }}>{tpl.party[lang] || tpl.party.fr}</div>
                  <div style={{ marginTop: 12, display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12, color: tpl.color, fontWeight: 600 }}>{t("Rédiger & signer","Draft & sign")} →</div>
                </Card>
              ))}
            </div>
          </>
        )}

        {/* Existing */}
        <Label style={{ marginBottom: 12 }}>{t("DOCUMENTS EXISTANTS","EXISTING DOCUMENTS")}</Label>
        <Card style={{ padding: 0, overflow: "hidden" }}>
          {list.map((c, i) => {
            const tpl = tplOf(c.tpl) || CONTRACT_TEMPLATES[0];
            return (
              <div key={c.id} style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 20px", borderTop: i === 0 ? "none" : `1px solid ${C.softLine}` }}>
                <div style={{ width: 38, height: 38, borderRadius: 10, background: tpl.color === "#0B0F1F" ? C.ink : tpl.color + "22", color: tpl.color === "#0B0F1F" ? C.flame : tpl.color, display: "grid", placeItems: "center", fontSize: 16 }}>{tpl.g}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>{c.title}</div>
                  <div style={{ fontSize: 12, color: C.slate }}>{c.other} · {c.date}</div>
                </div>
                {c.status === "signed"
                  ? <><Pill tone="signal">✓ {t("Signé","Signed")}</Pill><Button size="sm" kind="ghost" onClick={() => toast.push(t("PDF téléchargé","PDF downloaded"), "signal")}>↓ PDF</Button></>
                  : <><Pill tone="flame">{t("À signer","To sign")}</Pill><Button size="sm" kind="primary" onClick={() => { setView(tplOf(c.tpl)); setSigned(false); setHasSig(false); }}>{t("Signer","Sign")}</Button></>}
              </div>
            );
          })}
        </Card>

        <div style={{ marginTop: 16, padding: 14, background: "#FBF8EE", borderRadius: 10, borderLeft: `3px solid ${C.flame}`, fontSize: 12.5, lineHeight: 1.5 }}>
          🔏 {t("Chaque signature est horodatée, chiffrée (SHA-256) et archivée. Valeur légale dans le pays de l'utilisateur.","Every signature is time-stamped, encrypted (SHA-256) and archived. Legally valid in the user's country.")}
        </div>
      </PageBody>
    </>
  );
}

window.ContractsPage = ContractsPage;
