import { useState, useRef } from "react";

const BAREME_KM = [
    { cv: 3, label: "3 CV et moins", t1: 0.529, t2_a: 0.316, t2_b: 1061, t3: 0.369 },
    { cv: 4, label: "4 CV", t1: 0.606, t2_a: 0.340, t2_b: 1330, t3: 0.408 },
    { cv: 5, label: "5 CV", t1: 0.636, t2_a: 0.356, t2_b: 1391, t3: 0.427 },
    { cv: 6, label: "6 CV", t1: 0.665, t2_a: 0.374, t2_b: 1457, t3: 0.448 },
    { cv: 7, label: "7 CV et plus", t1: 0.697, t2_a: 0.394, t2_b: 1512, t3: 0.470 },
];

const CATEGORIES_DEFAULT = ["Deplacement kilometrique", "Repas", "Hebergement", "Transport", "Autre"];

const TAUX_TVA = [
    { taux: 0, libelle: "Exonéré (0%)" },
    { taux: 10, libelle: "Taux réduit (10%)" },
    { taux: 15, libelle: "Taux intermédiaire (15%)" },
    { taux: 20, libelle: "Taux normal (20%)" },
];

function fmt(val) {
    return new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR" }).format(val);
}
function getHT(ttc, taux) { return ttc / (1 + taux / 100); }
function getTVA(ttc, taux) { return ttc - getHT(ttc, taux); }
function calcIndemnite(km, cv) {
    const b = BAREME_KM.find(r => r.cv === cv) ?? BAREME_KM[4];
    if (km <= 0) return 0;
    if (km <= 5000) return parseFloat((km * b.t1).toFixed(2));
    if (km <= 20000) return parseFloat((km * b.t2_a + b.t2_b).toFixed(2));
    return parseFloat((km * b.t3).toFixed(2));
}
function getTranche(km) {
    if (km <= 0) return 0;
    if (km <= 5000) return 1;
    if (km <= 20000) return 2;
    return 3;
}

function newDepense() {
    return {
        id: Math.random(),
        categorie: "Repas",
        date: "",
        libelle: "",
        description: "",
        km: "",
        // FIX 1 : chevaux stocké en number pour cohérence avec BAREME_KM
        chevaux: 7,
        // FIX 2 : taux initial aligné avec les options TAUX_TVA (on utilise "" pour forcer un choix explicite)
        tvaItems: [{ taux: "", montantTTC: "" }],
        nombreParticipants: "",
        participants: [{ nom: "", prenom: "", societe: "" }],
        files: [],
    };
}

const css = `
  @import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700;800&display=swap');

  * { box-sizing: border-box; margin: 0; padding: 0; }

  :root {
    --bg: #f4f4f5;
    --bg-card: #ffffff;
    --bg-input: #f9f9fa;
    --bg-sidebar: #ffffff;
    --border: rgba(0,0,0,0.07);
    --border-light: rgba(0,0,0,0.11);
    --text-primary: #111111;
    --text-secondary: #6b7280;
    --accent-orange: #c8933a;
    --accent-purple: #7c3aed;
    --accent-green: #16a34a;
    --accent-indigo: #4f46e5;
    --accent-yellow: #d97706;
    font-family: 'DM Sans', sans-serif;
  }

  body { background: var(--bg); color: var(--text-primary); min-height: 100vh; }

  .app { display: flex; min-height: 100vh; }

  /* ── Main ── */
  .main { flex: 1; padding: 28px; max-width: 740px; }

  /* ── Header ── */
  .header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 28px; }
  .header-left { display: flex; align-items: center; gap: 14px; }
  .header-title { font-size: 20px; font-weight: 800; color: var(--text-primary); }
  .badge-brouillon {
    background: rgba(200,147,58,0.12);
    color: var(--accent-orange);
    border: 1px solid rgba(200,147,58,0.35);
    border-radius: 20px;
    padding: 4px 14px;
    font-size: 12px;
    font-weight: 700;
  }
  .btn-save {
    background: #111111;
    color: #ffffff;
    border: none;
    border-radius: 10px;
    padding: 10px 24px;
    font-size: 14px;
    font-weight: 700;
    cursor: pointer;
    font-family: inherit;
    transition: opacity 0.15s;
  }
  .btn-save:hover { opacity: 0.85; }

  /* ── Meta fields ── */
  .meta-grid {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 100px;
    gap: 12px;
    align-items: start;
    margin-bottom: 24px;
    background: var(--bg-card);
    border: 1px solid var(--border-light);
    border-radius: 14px;
    padding: 18px;
  }
  .meta-label { font-size: 11px; font-weight: 700; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em; line-height: 1.3; margin-bottom: 6px; }
  .meta-label span { color: #ef4444; }

  .input-field {
    background: var(--bg-input);
    border: 1px solid var(--border-light);
    border-radius: 8px;
    padding: 10px 14px;
    font-size: 13px;
    font-family: inherit;
    color: var(--text-primary);
    width: 100%;
    outline: none;
    transition: border-color 0.15s;
  }
  .input-field:focus { border-color: rgba(0,0,0,0.25); }
  .input-field::placeholder { color: var(--text-secondary); }

  .logo-box {
    width: 52px; height: 52px;
    background: var(--bg-input);
    border: 1px solid var(--border-light);
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    cursor: pointer;
    font-size: 22px;
    transition: border-color 0.15s;
  }
  .logo-box:hover { border-color: rgba(0,0,0,0.25); }

  /* ── Section Dépenses ── */
  .section-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; }
  .section-title { font-size: 11px; font-weight: 800; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.1em; }
  .btn-add-depense {
    background: #111111;
    color: #ffffff;
    border: none;
    border-radius: 10px;
    padding: 10px 20px;
    font-size: 13px;
    font-weight: 700;
    cursor: pointer;
    font-family: inherit;
    transition: opacity 0.15s;
  }
  .btn-add-depense:hover { opacity: 0.85; }

  /* ── Dépense card ── */
  .depense-card {
    border: 1px solid var(--border-light);
    border-radius: 14px;
    overflow: hidden;
    background: var(--bg-card);
    margin-bottom: 16px;
    box-shadow: 0 1px 4px rgba(0,0,0,0.08);
  }

  .card-header {
    display: flex; align-items: center; justify-content: space-between;
    padding: 14px 18px;
    border-bottom: 1px solid var(--border);
  }
  .card-header-left { display: flex; align-items: center; gap: 10px; }
  .dot-orange { width: 10px; height: 10px; border-radius: 50%; background: var(--accent-orange); flex-shrink: 0; }
  .card-title { font-size: 13px; font-weight: 700; color: var(--text-primary); line-height: 1.2; }
  .card-subtitle { font-size: 11px; color: var(--text-secondary); margin-top: 2px; }
  .card-header-right { display: flex; align-items: center; gap: 10px; }
  .status-chip { font-size: 12px; color: var(--text-secondary); font-weight: 500; }

  .card-body { padding: 18px; display: flex; flex-direction: column; gap: 16px; }

  .form-grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
  .form-label { font-size: 11px; font-weight: 700; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.04em; display: block; margin-bottom: 6px; }

  select.input-field { appearance: none; cursor: pointer; padding-right: 32px; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23888' stroke-width='2'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 10px center; }

  /* ── TVA block ── */
  .tva-block {
    background: var(--bg-input);
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 14px;
  }
  .tva-block-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; }
  .tva-block-title { font-size: 12px; font-weight: 700; color: var(--text-secondary); }
  .btn-ajouter-taux {
    display: flex; align-items: center; gap: 6px;
    padding: 6px 14px;
    background: rgba(255,255,255,0.07);
    border: 1px solid var(--border-light);
    border-radius: 7px;
    cursor: pointer;
    font-size: 12px;
    color: var(--text-primary);
    font-weight: 600;
    font-family: inherit;
    transition: background 0.15s;
  }
  .btn-ajouter-taux:hover { background: rgba(0,0,0,0.05); }

  .tva-cols { display: grid; grid-template-columns: 1fr 1fr 80px 80px 32px; gap: 8px; margin-bottom: 6px; align-items: center; }
  .tva-col-label { font-size: 10px; font-weight: 700; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.04em; }

  .tva-val { display: flex; align-items: center; justify-content: center; height: 38px; font-size: 13px; font-weight: 700; }
  .tva-val.green { color: #7c3aed; }
  .tva-val.indigo { color: #4f46e5; }
  .tva-val.muted { color: var(--text-secondary); }

  .btn-remove {
    width: 28px; height: 28px; border-radius: 6px; border: none;
    background: rgba(220,38,38,0.1);
    color: #dc2626;
    cursor: pointer;
    display: flex; align-items: center; justify-content: center;
    font-size: 13px;
    transition: background 0.15s;
    font-family: inherit;
  }
  .btn-remove:hover { background: rgba(220,38,38,0.2); }
  .btn-remove:disabled { background: transparent; color: rgba(0,0,0,0.15); cursor: default; }

  .totals-row {
    margin-top: 12px; padding: 10px 14px;
    background: rgba(0,0,0,0.02);
    border: 1px solid var(--border);
    border-radius: 8px;
    display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px;
  }
  .total-col { text-align: center; }
  .total-col + .total-col { border-left: 1px solid var(--border); }
  .total-col-label { font-size: 9px; font-weight: 700; color: var(--text-secondary); text-transform: uppercase; margin-bottom: 3px; }
  .total-col-val { font-size: 14px; font-weight: 900; }

  /* ── Repas block ── */
  .repas-block {
    background: rgba(124,58,237,0.05);
    border: 1.5px solid rgba(124,58,237,0.2);
    border-radius: 10px; padding: 14px;
  }
  .repas-title { font-size: 12px; font-weight: 700; color: #7c3aed; margin-bottom: 10px; display: flex; align-items: center; justify-content: space-between; }

  /* ── KM block ── */
  .km-block {
    background: rgba(124,58,237,0.05);
    border: 1.5px solid rgba(124,58,237,0.2);
    border-radius: 10px; padding: 16px;
  }
  .km-title { font-size: 12px; font-weight: 800; color: #7c3aed; margin-bottom: 14px; }
  .km-table { width: 100%; border-collapse: collapse; font-size: 12px; overflow: hidden; border-radius: 8px; margin-bottom: 16px; }
  .km-table thead tr { background: #7c3aed; }
  .km-table thead th { padding: 8px 12px; color: #fff; font-weight: 700; text-align: left; }
  .km-table thead th:not(:first-child) { text-align: center; }
  .km-table tbody tr { cursor: pointer; transition: background 0.1s; }
  .km-table tbody td { padding: 10px 12px; color: var(--text-secondary); }
  .km-table tbody td:not(:first-child) { text-align: center; }
  .km-table tbody tr.selected { background: rgba(124,58,237,0.12); outline: 2px solid #7c3aed; outline-offset: -1px; }
  .km-table tbody tr.selected td { color: #7c3aed; font-weight: 800; }
  .km-active-badge { font-size: 9px; color: #7c3aed; font-weight: 700; }

  .indemnite-box {
    padding: 10px 16px;
    min-height: 42px;
    border-radius: 8px;
    border: 1.5px solid rgba(124,58,237,0.3);
    display: flex; align-items: center; justify-content: space-between;
  }
  .indemnite-box.active { background: linear-gradient(135deg, #7c3aed, #5b21b6); }
  .indemnite-box.empty { background: rgba(124,58,237,0.05); }

  /* ── Justificatif ── */
  .drop-zone {
    border: 1.5px dashed rgba(0,0,0,0.15);
    border-radius: 8px;
    padding: 16px;
    text-align: center;
    cursor: pointer;
    font-size: 12px;
    color: var(--text-secondary);
    font-weight: 500;
    transition: all 0.2s;
  }
  .drop-zone:hover { border-color: rgba(0,0,0,0.3); }
  .drop-zone.has-files { border-color: rgba(22,163,74,0.5); color: var(--accent-green); }

  /* ── Btn supprimer ── */
  .btn-supprimer {
    width: 100%; padding: 12px;
    background: rgba(0,0,0,0.02);
    border: 1px solid rgba(0,0,0,0.08);
    border-radius: 8px;
    cursor: pointer;
    color: var(--text-primary);
    font-size: 13px; font-weight: 600;
    font-family: inherit;
    transition: background 0.15s;
  }
  .btn-supprimer:hover { background: rgba(220,38,38,0.06); border-color: rgba(220,38,38,0.3); color: #dc2626; }

  /* ── Sidebar ── */
  .sidebar {
    width: 280px;
    background: var(--bg-sidebar);
    border-left: 1px solid var(--border);
    padding: 24px 20px;
    display: flex;
    flex-direction: column;
    gap: 12px;
    position: sticky;
    top: 0;
    height: 100vh;
    overflow-y: auto;
  }
  .sidebar-title { font-size: 11px; font-weight: 800; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.1em; margin-bottom: 8px; }

  .recap-item {
    display: flex; align-items: flex-start; gap: 10px;
    padding: 10px 12px;
    border-radius: 8px;
    background: rgba(0,0,0,0.03);
  }
  .recap-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--accent-orange); flex-shrink: 0; margin-top: 3px; }
  .recap-label { font-size: 13px; font-weight: 700; color: var(--text-primary); }
  .recap-cat { font-size: 11px; color: var(--text-secondary); margin-top: 1px; }

  .sidebar-totals { margin-top: auto; }
  .sidebar-totals-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid var(--border); font-size: 13px; color: var(--text-secondary); font-weight: 500; }
  .sidebar-totals-main { display: flex; justify-content: space-between; padding: 12px 0; font-size: 15px; font-weight: 800; color: var(--text-primary); }

  .btn-soumettre {
    width: 100%;
    padding: 13px;
    background: #111111;
    color: #ffffff;
    border: none;
    border-radius: 10px;
    font-size: 14px; font-weight: 800;
    cursor: pointer;
    font-family: inherit;
    transition: opacity 0.15s;
    margin-top: 8px;
  }
  .btn-soumettre:hover { opacity: 0.85; }
  .btn-soumettre-note { font-size: 11px; color: var(--text-secondary); text-align: center; margin-top: 6px; }

  .input-with-suffix { position: relative; }
  .input-with-suffix .suffix { position: absolute; right: 12px; top: 50%; transform: translateY(-50%); font-size: 11px; color: var(--accent-purple); font-weight: 700; pointer-events: none; }
  .input-with-suffix .suffix-eur { color: var(--text-secondary); }
`;

function DepenseCard({ depense, total, onChange, onDelete }) {
    const fileRef = useRef();
    const isKm = depense.categorie.toLowerCase().includes("kilom");
    const isRepas = depense.categorie.toLowerCase().includes("repas");

    const kmNum = parseFloat(depense.km) || 0;
    // FIX 1 : chevaux est maintenant un number, parseInt reste en sécurité
    const cv = typeof depense.chevaux === "number" ? depense.chevaux : parseInt(depense.chevaux) || 7;
    const tranche = getTranche(kmNum);
    const indemnite = calcIndemnite(kmNum, cv);

    const tvaItems = depense.tvaItems?.length ? depense.tvaItems : [{ taux: "", montantTTC: "" }];
    const totalTTC = isKm ? indemnite : tvaItems.reduce((s, i) => s + (parseFloat(i.montantTTC) || 0), 0);
    const totalHT = isKm ? indemnite : tvaItems.reduce((s, i) => {
        const t = parseFloat(i.montantTTC) || 0; const tx = parseFloat(i.taux) || 0;
        return s + (tx > 0 ? getHT(t, tx) : t);
    }, 0);
    const totalTVA = isKm ? 0 : tvaItems.reduce((s, i) => {
        const t = parseFloat(i.montantTTC) || 0; const tx = parseFloat(i.taux) || 0;
        return s + (tx > 0 ? getTVA(t, tx) : 0);
    }, 0);

    const updateTvaItem = (idx, field, val) => {
        const copy = [...tvaItems];
        copy[idx] = { ...copy[idx], [field]: val };
        // FIX 2 : suppression du onChange("montant", ...) — ce champ n'existe pas dans le modèle
        onChange("tvaItems", copy);
    };

    const addTvaItem = () => onChange("tvaItems", [...tvaItems, { taux: "", montantTTC: "" }]);
    const removeTvaItem = (idx) => {
        if (tvaItems.length <= 1) return;
        const copy = tvaItems.filter((_, i) => i !== idx);
        // FIX 2 (suite) : suppression du onChange("montant", ...) orphelin
        onChange("tvaItems", copy);
    };

    const updateParticipant = (i, field, val) => {
        const updated = [...depense.participants];
        updated[i] = { ...updated[i], [field]: val };
        onChange("participants", updated);
    };

    const addFiles = (list) => {
        if (!list) return;
        const allowed = ["image/jpeg", "image/jpg", "image/png", "application/pdf"];
        onChange("files", [...depense.files, ...Array.from(list).filter(f => allowed.includes(f.type))]);
    };

    return (
        <div className="depense-card">
            {/* Header */}
            <div className="card-header">
                <div className="card-header-left">
                    <div className="dot-orange" />
                    <div>
                        <div className="card-title">Nouvelle dépense</div>
                        <div className="card-subtitle">{depense.categorie || "Sans catégorie"}</div>
                    </div>
                </div>
                <div className="card-header-right">
                    <span className="status-chip">À saisir</span>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#888" strokeWidth="2"><path d="M18 15l-6-6-6 6" /></svg>
                </div>
            </div>

            {/* Body */}
            <div className="card-body">
                {/* Catégorie + Date */}
                <div className="form-grid-2">
                    <div>
                        <label className="form-label">Catégorie *</label>
                        <select className="input-field" value={depense.categorie}
                            onChange={e => {
                                onChange("categorie", e.target.value);
                                onChange("km", "");
                                onChange("tvaItems", [{ taux: "", montantTTC: "" }]);
                            }}>
                            {CATEGORIES_DEFAULT.map(c => <option key={c} value={c}>{c}</option>)}
                        </select>
                    </div>
                    <div>
                        <label className="form-label">Date *</label>
                        <input type="date" className="input-field" value={depense.date} onChange={e => onChange("date", e.target.value)} />
                    </div>
                </div>

                {/* Libellé */}
                <div>
                    <label className="form-label">Libellé *</label>
                    <input className="input-field" value={depense.libelle} onChange={e => onChange("libelle", e.target.value)} placeholder="Ex: Déjeuner client, Train Paris-Lyon..." />
                </div>

                {/* Commentaire */}
                <div>
                    <label className="form-label">Commentaire (optionnel)</label>
                    <input className="input-field" value={depense.description} onChange={e => onChange("description", e.target.value)} placeholder="Précision, contexte..." />
                </div>

                {/* KM block */}
                {isKm && (
                    <div className="km-block">
                        <div className="km-title">🚗 Barème kilométrique fiscal</div>
                        <div style={{ overflowX: "auto" }}>
                            <table className="km-table">
                                <thead>
                                    <tr>
                                        <th>Puissance fiscale</th>
                                        <th>≤ 5 000 km</th>
                                        <th>5 001 → 20 000 km</th>
                                        <th>&gt; 20 000 km</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {BAREME_KM.map((b) => {
                                        const sel = cv === b.cv;
                                        return (
                                            <tr key={b.cv} className={sel ? "selected" : ""}
                                                // FIX 1 : on stocke un number, pas une string
                                                onClick={() => onChange("chevaux", b.cv)}>
                                                <td>{b.label}</td>
                                                <td>d × {b.t1.toString().replace(".", ",")}{sel && tranche === 1 && <div className="km-active-badge">▲ active</div>}</td>
                                                <td>(d × {b.t2_a.toString().replace(".", ",")}) + {b.t2_b.toLocaleString("fr-FR")}{sel && tranche === 2 && <div className="km-active-badge">▲ active</div>}</td>
                                                <td>d × {b.t3.toString().replace(".", ",")}{sel && tranche === 3 && <div className="km-active-badge">▲ active</div>}</td>
                                            </tr>
                                        );
                                    })}
                                </tbody>
                            </table>
                        </div>
                        <div className="form-grid-2">
                            <div>
                                <label className="form-label" style={{ color: "#7c3aed" }}>Nombre de kilomètres *</label>
                                <div className="input-with-suffix">
                                    <input type="number" min="0" className="input-field" style={{ borderColor: "rgba(124,58,237,0.4)", paddingRight: 40 }} value={depense.km} onChange={e => onChange("km", e.target.value)} placeholder="0" />
                                    <span className="suffix">km</span>
                                </div>
                                {kmNum > 0 && tranche > 0 && (
                                    <div style={{ marginTop: 5, fontSize: 10, color: "#7c3aed", fontWeight: 600 }}>
                                        🔢 Tranche {tranche} = <strong>{fmt(indemnite)}</strong>
                                    </div>
                                )}
                            </div>
                            <div>
                                <label className="form-label" style={{ color: "#7c3aed" }}>Indemnité calculée</label>
                                <div className={`indemnite-box ${indemnite > 0 ? "active" : "empty"}`}>
                                    <span style={{ fontSize: 18, fontWeight: 900, color: indemnite > 0 ? "#fff" : "#6b7280" }}>
                                        {indemnite > 0 ? fmt(indemnite) : "—"}
                                    </span>
                                    {kmNum > 0 && tranche > 0 && (
                                        <span style={{ fontSize: 10, color: "rgba(255,255,255,0.8)", fontWeight: 600, textAlign: "right" }}>
                                            {cv} CV<br />Tranche {tranche}
                                        </span>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>
                )}

                {/* TVA block */}
                {!isKm && (
                    <div className="tva-block">
                        <div className="tva-block-header">
                            <span className="tva-block-title">Montant &amp; TVA</span>
                            <button type="button" className="btn-ajouter-taux" onClick={addTvaItem}>
                                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M12 5v14M5 12h14" /></svg>
                                + Ajouter un taux
                            </button>
                        </div>
                        <div className="tva-cols" style={{ marginBottom: 8 }}>
                            <div className="tva-col-label">Taux TVA</div>
                            <div className="tva-col-label">Montant TTC</div>
                            <div className="tva-col-label">HT</div>
                            <div className="tva-col-label">TVA</div>
                            <div />
                        </div>
                        {tvaItems.map((item, idx) => {
                            const ttc = parseFloat(item.montantTTC) || 0;
                            const taux = parseFloat(item.taux) || 0;
                            const ht = taux > 0 ? getHT(ttc, taux) : ttc;
                            const tva = taux > 0 ? getTVA(ttc, taux) : 0;
                            return (
                                <div key={idx} className="tva-cols" style={{ marginBottom: 8, alignItems: "center" }}>
                                    {/* FIX 2 : option vide cohérente avec le state initial taux: "" */}
                                    <select className="input-field" value={item.taux} onChange={e => updateTvaItem(idx, "taux", e.target.value)}>
                                        <option value="">— Choisir un taux —</option>
                                        {TAUX_TVA.map((t, i) => <option key={i} value={String(t.taux)}>{t.taux}% — {t.libelle}</option>)}
                                    </select>
                                    <div className="input-with-suffix">
                                        <input type="number" min="0" step="0.01" className="input-field" style={{ paddingRight: 28 }} value={item.montantTTC} onChange={e => updateTvaItem(idx, "montantTTC", e.target.value)} placeholder="0,00" />
                                        <span className="suffix suffix-eur">€</span>
                                    </div>
                                    <div className={`tva-val ${ttc > 0 ? "green" : "muted"}`}>{ttc > 0 ? fmt(ht) : "—"}</div>
                                    <div className={`tva-val ${tva > 0 ? "indigo" : "muted"}`}>{tva > 0 ? fmt(tva) : "—"}</div>
                                    <button type="button" className="btn-remove" disabled={tvaItems.length <= 1} onClick={() => removeTvaItem(idx)}>✕</button>
                                </div>
                            );
                        })}
                        {tvaItems.length > 1 && totalTTC > 0 && (
                            <div className="totals-row">
                                <div className="total-col"><div className="total-col-label">Total HT</div><div className="total-col-val" style={{ color: "#7c3aed" }}>{fmt(totalHT)}</div></div>
                                <div className="total-col"><div className="total-col-label">Total TVA</div><div className="total-col-val" style={{ color: "#4f46e5" }}>{fmt(totalTVA)}</div></div>
                                <div className="total-col"><div className="total-col-label">Total TTC</div><div className="total-col-val" style={{ color: "var(--text-primary)" }}>{fmt(totalTTC)}</div></div>
                            </div>
                        )}
                    </div>
                )}

                {/* Participants (repas) */}
                {isRepas && (
                    <div className="repas-block">
                        <div className="repas-title">
                            🍽️ Participants au repas
                        </div>
                        <div style={{ marginBottom: 10 }}>
                            <label className="form-label" style={{ color: "#7c3aed" }}>Nombre de participants *</label>
                            <input type="number" min="1" className="input-field" style={{ borderColor: "rgba(124,58,237,0.3)" }} value={depense.nombreParticipants} onChange={e => onChange("nombreParticipants", e.target.value)} placeholder="Ex: 3" />
                        </div>
                        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                            {depense.participants.map((p, i) => (
                                <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr auto", gap: 8, alignItems: "end" }}>
                                    <div>
                                        {i === 0 && <div className="form-label" style={{ color: "#7c3aed" }}>Nom *</div>}
                                        <input className="input-field" style={{ borderColor: "rgba(124,58,237,0.3)" }} value={p.nom} onChange={e => updateParticipant(i, "nom", e.target.value)} placeholder="Nom" />
                                    </div>
                                    <div>
                                        {i === 0 && <div className="form-label" style={{ color: "#7c3aed" }}>Prénom *</div>}
                                        <input className="input-field" style={{ borderColor: "rgba(124,58,237,0.3)" }} value={p.prenom} onChange={e => updateParticipant(i, "prenom", e.target.value)} placeholder="Prénom" />
                                    </div>
                                    <div>
                                        {i === 0 && <div className="form-label" style={{ color: "#7c3aed" }}>Société</div>}
                                        <input className="input-field" style={{ borderColor: "rgba(124,58,237,0.3)" }} value={p.societe || ""} onChange={e => updateParticipant(i, "societe", e.target.value)} placeholder="Société (opt.)" />
                                    </div>
                                    {depense.participants.length > 1 && (
                                        <button className="btn-remove" onClick={() => onChange("participants", depense.participants.filter((_, j) => j !== i))}>✕</button>
                                    )}
                                </div>
                            ))}
                        </div>
                        <button type="button" onClick={() => onChange("participants", [...depense.participants, { nom: "", prenom: "", societe: "" }])}
                            style={{ marginTop: 8, background: "none", border: "1px dashed rgba(124,58,237,0.35)", borderRadius: 6, padding: "6px 12px", cursor: "pointer", fontSize: 11, color: "#7c3aed", fontWeight: 600, fontFamily: "inherit" }}>
                            + Ajouter un participant
                        </button>
                    </div>
                )}

                {/* Justificatif */}
                <div>
                    <label className="form-label">Justificatif{isKm ? " (facultatif)" : ""}</label>
                    <div className={`drop-zone ${depense.files.length > 0 ? "has-files" : ""}`}
                        onClick={() => fileRef.current?.click()}
                        onDragOver={e => e.preventDefault()}
                        onDrop={e => { e.preventDefault(); addFiles(e.dataTransfer.files); }}>
                        {depense.files.length > 0 ? `${depense.files.length} fichier${depense.files.length > 1 ? "s" : ""} joint${depense.files.length > 1 ? "s" : ""}` : "Glisser un fichier ou cliquer — PDF, JPG, PNG"}
                        <input ref={fileRef} type="file" multiple accept=".pdf,.jpg,.jpeg,.png" onChange={e => addFiles(e.target.files)} style={{ display: "none" }} />
                    </div>
                    {isKm && depense.files.length === 0 && (
                        <div style={{ marginTop: 8, background: "rgba(124,58,237,0.05)", border: "1px solid rgba(124,58,237,0.2)", borderRadius: 8, padding: "8px 12px", fontSize: 11, color: "#7c3aed", fontWeight: 600 }}>
                            Déplacement kilométrique — le justificatif est facultatif
                        </div>
                    )}
                </div>

                {/* Supprimer */}
                {total > 1 && (
                    <button className="btn-supprimer" onClick={onDelete}>Supprimer cette dépense</button>
                )}
            </div>
        </div>
    );
}

export default function App() {
    // FIX 3 : titre est maintenant lié à un vrai <input> dans le JSX
    const [titre, setTitre] = useState("");
    const [dateDebut, setDateDebut] = useState("");
    const [dateFin, setDateFin] = useState("");
    const [commentaire, setCommentaire] = useState("");
    const [depenses, setDepenses] = useState([newDepense()]);

    const updateDepense = (id, field, val) => {
        setDepenses(prev => prev.map(d => d.id === id ? { ...d, [field]: val } : d));
    };
    const deleteDepense = (id) => setDepenses(prev => prev.filter(d => d.id !== id));
    const addDepense = () => setDepenses(prev => [...prev, newDepense()]);

    // Totaux sidebar
    const totalTTC = depenses.reduce((s, d) => {
        const isKm = d.categorie.toLowerCase().includes("kilom");
        if (isKm) return s + calcIndemnite(parseFloat(d.km) || 0, typeof d.chevaux === "number" ? d.chevaux : parseInt(d.chevaux) || 7);
        return s + (d.tvaItems || []).reduce((ss, i) => ss + (parseFloat(i.montantTTC) || 0), 0);
    }, 0);
    const totalHT = depenses.reduce((s, d) => {
        const isKm = d.categorie.toLowerCase().includes("kilom");
        if (isKm) return s + calcIndemnite(parseFloat(d.km) || 0, typeof d.chevaux === "number" ? d.chevaux : parseInt(d.chevaux) || 7);
        return s + (d.tvaItems || []).reduce((ss, i) => {
            const t = parseFloat(i.montantTTC) || 0; const tx = parseFloat(i.taux) || 0;
            return ss + (tx > 0 ? getHT(t, tx) : t);
        }, 0);
    }, 0);
    const totalTVA = totalTTC - totalHT;

    return (
        <>
            <style>{css}</style>
            <div className="app">
                {/* Main */}
                <div className="main">
                    {/* Header */}
                    <div className="header">
                        <div className="header-left">
                            <span className="header-title">Nouvelle note de frais</span>
                            <span className="badge-brouillon">Brouillon</span>
                        </div>
                        <button className="btn-save">Enregistrer</button>
                    </div>

                    {/* Meta — FIX 3 : champ titre désormais fonctionnel avec input lié */}
                    <div className="meta-grid">
                        <div>
                            <div className="meta-label">Titre <span>*</span></div>
                            <input
                                className="input-field"
                                value={titre}
                                onChange={e => setTitre(e.target.value)}
                                placeholder="Ex: Mission Lyon mars"
                            />
                        </div>
                        <div>
                            <div style={{ fontSize: 11, fontWeight: 700, color: "var(--text-secondary)", marginBottom: 6, textTransform: "uppercase" }}>Période</div>
                            <div style={{ display: "flex", gap: 8 }}>
                                <input type="date" className="input-field" value={dateDebut} onChange={e => setDateDebut(e.target.value)} style={{ flex: 1 }} />
                                <input type="date" className="input-field" value={dateFin} onChange={e => setDateFin(e.target.value)} style={{ flex: 1 }} />
                            </div>
                        </div>
                        <div>
                            <div style={{ fontSize: 11, fontWeight: 700, color: "var(--text-secondary)", marginBottom: 6, textTransform: "uppercase" }}>Commentaire</div>
                            <input className="input-field" value={commentaire} onChange={e => setCommentaire(e.target.value)} placeholder="Projet" />
                        </div>
                        <div>
                            <div className="logo-box" title="Ajouter un logo">🏢</div>
                        </div>
                    </div>

                    {/* Dépenses */}
                    <div className="section-header">
                        <span className="section-title">Dépenses</span>
                        <button className="btn-add-depense" onClick={addDepense}>+ Ajouter une dépense</button>
                    </div>

                    {depenses.map(d => (
                        <DepenseCard
                            key={d.id}
                            depense={d}
                            total={depenses.length}
                            onChange={(field, val) => updateDepense(d.id, field, val)}
                            onDelete={() => deleteDepense(d.id)}
                        />
                    ))}
                </div>

                {/* Sidebar */}
                <div className="sidebar">
                    <div className="sidebar-title">Récapitulatif</div>
                    {depenses.map(d => (
                        <div className="recap-item" key={d.id}>
                            <div className="recap-dot" />
                            <div>
                                <div className="recap-label">{d.libelle || "Sans libellé"}</div>
                                <div className="recap-cat">{d.categorie}</div>
                            </div>
                        </div>
                    ))}

                    <div className="sidebar-totals">
                        <div className="sidebar-totals-row">
                            <span>Total HT</span>
                            <span style={{ color: "var(--text-primary)", fontWeight: 700 }}>{totalHT > 0 ? fmt(totalHT) : "—"}</span>
                        </div>
                        <div className="sidebar-totals-row">
                            <span>Total TVA</span>
                            <span style={{ color: "var(--text-primary)", fontWeight: 700 }}>{totalTVA > 0 ? fmt(totalTVA) : "—"}</span>
                        </div>
                        <div className="sidebar-totals-main">
                            <span>Total TTC</span>
                            <span>{totalTTC > 0 ? fmt(totalTTC) : "—"}</span>
                        </div>
                        <button className="btn-soumettre">Soumettre la note ↗</button>
                        <div className="btn-soumettre-note">Justificatifs vérifiés avant validation</div>
                    </div>
                </div>
            </div>
        </>
    );
}