/* Ingest screen — real file upload (drag-and-drop / browse) + simulated email demo.
   Real files are sent to the backend, which runs the extraction pipeline. */

const IngestView = ({ onProcessed }) => {
  const [over, setOver] = React.useState(false);
  const [phase, setPhase] = React.useState("idle"); // idle | processing
  const [step, setStep] = React.useState(0);
  const [files, setFiles] = React.useState([]);
  const inputRef = React.useRef(null);

  const sampleFiles = [
    { name: "Facture INV-2026-77231.pdf", size: "248 Ko", kind: "pdf" },
    { name: "Liste de colisage PKL-77231.pdf", size: "117 Ko", kind: "pdf" },
    { name: "IMG_8842.jpg — BL manuscrit", size: "2.8 Mo", kind: "image" },
  ];

  const steps = [
    "Téléversement des documents",
    "Rastérisation des PDF en images",
    "Lecture par le modèle de vision (GPT-4o)",
    "Extraction des 24 boîtes CMR",
    "Croisement des sources & scores de confiance",
    "Brouillon prêt pour validation",
  ];

  // Cosmetic stepper while the real extraction request is in flight.
  React.useEffect(() => {
    if (phase !== "processing") return;
    const t = setTimeout(() => setStep((s) => Math.min(s + 1, steps.length - 1)), 1100);
    return () => clearTimeout(t);
  }, [phase, step]);

  const kindOf = (name) => /\.(png|jpe?g|webp|tiff?|heic)$/i.test(name) ? "image"
    : /\.pdf$/i.test(name) ? "pdf" : "file";
  const fmtSize = (b) => b > 1e6 ? `${(b / 1e6).toFixed(1)} Mo` : `${Math.max(1, Math.round(b / 1e3))} Ko`;

  const submit = (fileList) => {
    setPhase("processing");
    setStep(0);
    onProcessed(fileList); // App runs extraction (or the demo) and navigates away
  };

  const onPick = (fileList) => {
    const arr = Array.from(fileList || []);
    if (!arr.length) return;
    setFiles(arr.map((f) => ({ name: f.name, size: fmtSize(f.size), kind: kindOf(f.name) })));
    submit(arr);
  };

  return (
    <div className="page">
      <header>
        <div>
          <h1>Nouveau dossier CMR</h1>
          <div className="sub">Déposez les documents — l'IA extrait, vous validez.</div>
        </div>
        <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
          <button className="btn ghost">Annuler</button>
        </div>
      </header>

      {phase === "idle" && (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
          {/* Upload */}
          <div className="card">
            <div className="card-head">
              <Icon name="upload" size={14} />
              <h3>Téléverser des documents</h3>
              <span className="sub">PDF, JPG, PNG · max 25 Mo</span>
            </div>
            <div className="card-body">
              <input ref={inputRef} type="file" multiple accept=".pdf,.png,.jpg,.jpeg,.webp,.tiff,.tif,.heic"
                style={{ display: "none" }} onChange={(e) => onPick(e.target.files)} />
              <div
                className={`dropzone ${over ? "over" : ""}`}
                onDragOver={(e) => { e.preventDefault(); setOver(true); }}
                onDragLeave={() => setOver(false)}
                onDrop={(e) => { e.preventDefault(); setOver(false); onPick(e.dataTransfer.files); }}
              >
                <div style={{ display: "flex", justifyContent: "center", marginBottom: 10 }}>
                  <div style={{ width: 48, height: 48, borderRadius: 12, background: "var(--accent-soft)", color: "var(--accent)", display: "grid", placeItems: "center" }}>
                    <Icon name="upload" size={22} />
                  </div>
                </div>
                <div className="big">Déposez vos documents ici</div>
                <div style={{ fontSize: 12.5 }}>Factures, bons de livraison, photos de paperasse…</div>
                <div style={{ marginTop: 14, display: "flex", gap: 8, justifyContent: "center" }}>
                  <button className="btn primary" onClick={() => inputRef.current && inputRef.current.click()}>Parcourir les fichiers</button>
                  <button className="btn" onClick={() => submit([])}>Essayer avec la démo</button>
                </div>
              </div>
              <div style={{ marginTop: 14, fontSize: 11.5, color: "var(--muted)" }}>
                Astuce — vous pouvez aussi transférer un email à <span className="mono" style={{ color: "var(--ink-2)" }}>ops+cargonote@atlas-maghreb.ma</span>
              </div>
            </div>
          </div>

          {/* Simulate email (demo) */}
          <div className="card">
            <div className="card-head">
              <Icon name="mail" size={14} />
              <h3>Simuler un email transféré</h3>
              <span className="sub">Démo</span>
            </div>
            <div className="card-body" style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              <Mailfield label="De" v="logistique@soremed.ma" />
              <Mailfield label="À" v="ops+cargonote@atlas-maghreb.ma" />
              <Mailfield label="Sujet" v="RE: Expédition #DK-88421 — Casablanca → Madrid" />
              <div>
                <div style={{ fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--muted)", marginBottom: 4 }}>Corps</div>
                <div style={{ background: "var(--surface-2)", border: "1px solid var(--hairline)", borderRadius: 6, padding: "10px 12px", fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.5, whiteSpace: "pre-wrap" }}>{`Bonjour,

Veuillez trouver ci-joint les documents pour l'expédition de demain : facture commerciale, liste de colisage et photo du BL signé.

— Enlèvement : 24/05/2026 au port de Casablanca
— Livraison : entrepôt Vallecas, Madrid (RDV — M. Martínez, +34 911 22 88 31)
— Tarif : franco, 2 850 € forfait porte-à-porte (cf. devis DV-2026-118)

Merci de confirmer la prise en charge.

Cordialement,
H. El Khattabi — Service logistique, SOREMED Industries`}</div>
              </div>
              <div>
                <div style={{ fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--muted)", marginBottom: 4 }}>Pièces jointes</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                  {sampleFiles.map((f) => (
                    <div key={f.name} style={{ display: "flex", alignItems: "center", gap: 8, padding: "6px 8px", background: "var(--surface-2)", border: "1px solid var(--hairline)", borderRadius: 6, fontSize: 12.5 }}>
                      <Icon name={f.kind === "image" ? "image" : "pdf"} size={14} style={{ color: "var(--muted)" }} />
                      <span style={{ flex: 1 }}>{f.name}</span>
                      <span className="mono" style={{ color: "var(--muted)", fontSize: 11 }}>{f.size}</span>
                    </div>
                  ))}
                </div>
              </div>
              <button className="btn accent" onClick={() => submit([])} style={{ alignSelf: "flex-start", marginTop: 4 }}>
                <Icon name="spark" size={14} /> Lancer la démo
              </button>
            </div>
          </div>
        </div>
      )}

      {phase === "processing" && (
        <div className="card" style={{ padding: 24 }}>
          <div className="proc-wrap">
            <div>
              <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--muted)" }}>État</div>
              <div style={{ fontSize: 18, fontWeight: 600, margin: "4px 0 16px" }}>Extraction en cours…</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {(files.length ? files : sampleFiles).map((f) => (
                  <div key={f.name} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5 }}>
                    <Icon name={f.kind === "image" ? "image" : "pdf"} size={14} style={{ color: "var(--muted)" }} />
                    <span style={{ flex: 1 }}>{f.name}</span>
                    <span className="mono" style={{ color: "var(--muted)", fontSize: 11 }}>{f.size}</span>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 16, fontSize: 12, color: "var(--muted)" }}>
                Le modèle de vision lit vos documents — cela prend quelques secondes.
              </div>
            </div>
            <div>
              <ol className="proc-steps">
                {steps.map((s, i) => {
                  const done = i < step;
                  const active = i === step;
                  return (
                    <li key={i} className={done ? "done" : active ? "active" : ""}>
                      <span className="marker">{done ? "✓" : active ? "" : i + 1}</span>
                      <span>{s}</span>
                    </li>
                  );
                })}
              </ol>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

const Mailfield = ({ label, v }) => (
  <div style={{ display: "grid", gridTemplateColumns: "60px 1fr", alignItems: "center", gap: 8 }}>
    <div style={{ fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--muted)" }}>{label}</div>
    <div className="mono" style={{ fontSize: 12.5, color: "var(--ink-2)" }}>{v}</div>
  </div>
);

window.IngestView = IngestView;
