// ============================================================
// Coccinelle — panneau fiche (identité, coordonnées, échange)
//               + bloc qualification
// ============================================================

/* ---------- minuterie d'appel ---------- */
function CallTimer({ resetKey }) {
  const [sec, setSec] = useState(0);
  useEffect(() => { setSec(0); const t = setInterval(() => setSec((s) => s + 1), 1000); return () => clearInterval(t); }, [resetKey]);
  const mm = String(Math.floor(sec / 60)).padStart(2, "0");
  const ss = String(sec % 60).padStart(2, "0");
  return (
    <div className="timer">
      <b>{mm}:{ss}</b>
      <span><i className="rec" /> En ligne</span>
    </div>
  );
}

/* ---------- en-tête de la fiche ---------- */
function FicheHeader({ fiche, tab, setTab, onChangeType, onChangeCanal, onCancel, qualified, qualReady, showTimer = true }) {
  const isCo = fiche.fields.civilite === "Société" || !!fiche.fields.societe;
  const cn = fiche.fields.clientNum;
  return (
    <div className="fiche-head">
      <div className="fiche-head-top">
        <div>
          <div className="fiche-id">
            <h1>{displayName(fiche)}</h1>
            {cn
              ? <span className="cn">{cn}</span>
              : <span className="cn new">Nouveau client</span>}
            {!qualified && onCancel && (
              <button type="button" className="fiche-cancel-btn" onClick={onCancel}
                title="Supprimer cette fiche créée par erreur"
                style={{ display: "inline-flex", alignItems: "center", gap: 5, marginLeft: 10, padding: "4px 10px", borderRadius: 8, border: "1px solid var(--line-strong)", background: "transparent", color: "var(--bad)", fontSize: 12.5, fontWeight: 600, cursor: "pointer" }}>
                <I.trash s={14} /> Annuler
              </button>
            )}
          </div>
          <div className="fiche-head-meta">
            {isCo ? <I.building s={15} /> : <I.user s={15} />}
            <span>{isCo ? "Professionnel" : "Particulier"}</span>
            <span style={{ color: "var(--line-strong)" }}>•</span>
            <I.phone s={14} /><span>{fiche.fields.tel || "Téléphone non renseigné"}</span>
            <span style={{ color: "var(--line-strong)" }}>•</span>
            <ChannelBadge canal={fiche.canal} size={13} />
          </div>
        </div>

        <div className="call-panel">
          <ChannelSelect canal={fiche.canal} onChange={onChangeCanal} disabled={qualified} compact />
          <div className="flux-toggle">
            <button className={fiche.type === "entrant" ? "on in" : ""} onClick={() => onChangeType("entrant")}>
              <I.phoneIn s={15} w={2} /> Entrant
            </button>
            <button className={fiche.type === "sortant" ? "on out" : ""} onClick={() => onChangeType("sortant")}>
              <I.phoneOut s={15} w={2} /> Sortant
            </button>
          </div>
          {!qualified && showTimer && <CallTimer resetKey={fiche.id} />}
        </div>
      </div>

      <div className="fiche-tabs">
        <button className={"fiche-tab" + (tab === "fiche" ? " on" : "")} onClick={() => setTab("fiche")}>
          <I.user s={16} /> Fiche client
        </button>
        <button className={"fiche-tab" + (tab === "qualif" ? " on" : "")} onClick={() => setTab("qualif")}>
          <I.flag s={16} /> Qualification
          {!qualReady && !qualified && <span className="req" title="Qualification requise" />}
        </button>
      </div>
    </div>
  );
}

/* ---------- formulaire fiche ---------- */
function SectionHead({ icon: Icon, title, opt }) {
  return (
    <div className="section-h">
      <span className="si"><Icon s={15} /></span>
      <h3>{title}</h3>
      {opt && <span className="opt">{opt}</span>}
    </div>
  );
}

function FicheForm({ fiche, set, readOnly }) {
  const f = fiche.fields;
  const isCo = f.civilite === "Société";
  const ro = readOnly ? { pointerEvents: "none", opacity: .72 } : null;
  return (
    <div className="fiche-grid" style={ro}>
      {/* Identité */}
      <div className="section">
        <SectionHead icon={isCo ? I.building : I.user} title="Identité" />
        <div className="field-row cpvl">
          <SelectField label="Civilité" required value={f.civilite}
            options={CIVILITES} onChange={(v) => set("civilite", v)} />
          <TextField label="Client n°" mono value={f.clientNum}
            placeholder="Si déjà client" onChange={(v) => set("clientNum", v)} />
        </div>
        {isCo ? (
          <>
            <TextField label="Société" required value={f.societe}
              placeholder="Raison sociale" onChange={(v) => set("societe", v)} />
            <TextField label="Matricule fiscale" mono value={f.matricule}
              placeholder="N° de TVA intracommunautaire" onChange={(v) => set("matricule", v)} />
          </>
        ) : (
          <div className="field-row c2">
            <TextField label="Nom" required value={f.nom}
              placeholder="Nom de famille" onChange={(v) => set("nom", v)} />
            <TextField label="Prénom" value={f.prenom}
              placeholder="Prénom" onChange={(v) => set("prenom", v)} />
          </div>
        )}
      </div>

      {/* Coordonnées */}
      <div className="section">
        <SectionHead icon={I.map} title="Coordonnées" />
        <TextField label="Adresse postale" value={f.adresse}
          placeholder="N° et libellé de voie" onChange={(v) => set("adresse", v)} />
        <div className="field-row c3">
          <TextField label="Code postal" mono value={f.cp}
            placeholder="00000" onChange={(v) => set("cp", v)} />
          <TextField label="Ville" value={f.ville}
            placeholder="Ville" onChange={(v) => set("ville", v)} />
        </div>
        <div className="field-row c2">
          <TextField label="Téléphone" required mono value={f.tel}
            placeholder="06 00 00 00 00" onChange={(v) => set("tel", v)} />
          <TextField label="Adresse mail" value={f.email}
            placeholder="nom@domaine.fr" onChange={(v) => set("email", v)} />
        </div>
      </div>

      {/* Échange */}
      <div className="section span2">
        <SectionHead icon={I.chat} title="Échange" opt="Champs libres" />
        <div className="field-row c2">
          <TextArea label="Motif d'appel" required value={f.motif} rows={4}
            placeholder="Raison de l'appel, demande du client…" onChange={(v) => set("motif", v)} />
          <TextArea label="Commentaire" value={f.commentaire} rows={4}
            placeholder="Notes internes, contexte, suite à donner…" onChange={(v) => set("commentaire", v)} />
        </div>
      </div>
    </div>
  );
}

/* ---------- bloc qualification ---------- */
function Qualification({ fiche, draft, setDraft }) {
  const op = useOp();
  const codes = op.forFlux(fiche.type);
  const groups = op.groups.filter((g) => codes.some((c) => c.group === g));
  const select = (code) => setDraft((d) => ({ ...d, code: d.code === code ? null : code, devis: "", rappelDate: "", rappelHeure: "", sav: "" }));
  const cur = draft.code ? op.byCode(draft.code) : null;

  return (
    <div className="qual-wrap">
      <div className="qual-intro">
        <span className="si" style={{ width: 32, height: 32, borderRadius: 9 }}><I.flag s={17} /></span>
        <div>
          <h2>Code conclusion — appel {fiche.type}</h2>
          <p>Sélectionnez le résultat de l'échange pour clôturer la fiche.</p>
        </div>
      </div>

      <div className="qual-groups">
        {groups.map((g) => (
          <div key={g}>
            <div className="qual-group-h">{g}</div>
            <div className="code-grid">
              {codes.filter((c) => c.group === g).map((c) => {
                const on = draft.code === c.code;
                return (
                  <button key={c.code} className={"code-card" + (on ? " on t-" + c.tone : "")}
                    onClick={() => select(c.code)}>
                    <span className="ck">{on && <I.checkBold s={13} />}</span>
                    <span className="ct">
                      <b>{c.label}</b>
                      <span>{c.sub}</span>
                    </span>
                  </button>
                );
              })}
            </div>
          </div>
        ))}
      </div>

      {/* champs conditionnels */}
      {cur && cur.needs === "rappel" && (
        <div className="cond">
          <h4><I.calendar s={15} /> Planifier le rappel</h4>
          <div className="field-row c2" style={{ maxWidth: 460 }}>
            <Field label="Date" required>
              <input type="date" value={draft.rappelDate}
                onChange={(e) => setDraft((d) => ({ ...d, rappelDate: e.target.value }))} />
            </Field>
            <Field label="Heure" required>
              <input type="time" value={draft.rappelHeure}
                onChange={(e) => setDraft((d) => ({ ...d, rappelHeure: e.target.value }))} />
            </Field>
          </div>
        </div>
      )}
      {cur && cur.needs === "devis" && (
        <div className="cond">
          <h4><I.doc s={15} /> Référence du devis</h4>
          <div style={{ maxWidth: 460 }}>
            <Field>
              <input className="mono" placeholder="N° devis ou objet (facultatif)"
                value={draft.devis} onChange={(e) => setDraft((d) => ({ ...d, devis: e.target.value }))}
                style={{ width: "100%", border: "1px solid var(--line-strong)", borderRadius: 8, padding: "9px 11px", fontSize: 13.5 }} />
            </Field>
          </div>
        </div>
      )}
      {cur && cur.needs === "sav" && (
        <div className="cond">
          <h4><I.wrench s={15} /> Nature de la demande SAV</h4>
          <div style={{ maxWidth: 560 }}>
            <input placeholder="Décrivez le problème à transmettre au SAV…"
              value={draft.sav} onChange={(e) => setDraft((d) => ({ ...d, sav: e.target.value }))}
              style={{ width: "100%", border: "1px solid var(--line-strong)", borderRadius: 8, padding: "9px 11px", fontSize: 13.5, fontFamily: "var(--font)" }} />
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { CallTimer, FicheHeader, SectionHead, FicheForm, Qualification });
