// ─── ContenuSite.jsx — Onglet « Contenu site » (édition du contenu PUBLIC) ────
// Pas de build, pas d'import/export — tout est global (React CDN).
//
// Édite UNIQUEMENT les champs publics affichés sur le site internet. Les
// documents (DPE actuel/projeté, descriptif des travaux, plan, attestation,
// photos) se TÉLÉVERSENT directement : ils sont stockés sur le serveur et servis
// par le site. Pas de OneDrive, aucun lien à coller.
// Les saves passent par /api/site-admin/* qui filtre les champs (whitelist serveur).

// Aide de saisie affichée sous les champs de texte libre : rappelle la mise en
// forme légère interprétée par le site public (cf. formatRichText dans site.js).
function FormatHint({ C }) {
  return (
    <div style={{ fontSize: 11, color: C.muted, marginTop: 4, lineHeight: 1.45 }}>
      Mise en forme&nbsp;: <b>**gras**</b>, <i>*italique*</i>. Sautez une ligne pour séparer les paragraphes.
    </div>
  );
}

// Téléverse un fichier et renvoie son URL (/uploads/site/…).
async function uploadSiteFile(file) {
  const fd = new FormData();
  fd.append('file', file);
  const r = await fetch('/api/site-admin/upload', { method: 'POST', body: fd });
  const d = await r.json().catch(() => ({}));
  if (!r.ok) throw new Error(d.error || 'Téléversement échoué');
  return d.url;
}

// Champ de téléversement d'un document unique (PDF / image / Word).
function SiteDocField({ C, label, value, accept, onChange }) {
  const [busy, setBusy] = React.useState(false);
  const [err, setErr]   = React.useState('');
  const ref = React.useRef(null);
  async function pick(e) {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    setBusy(true); setErr('');
    try { onChange(await uploadSiteFile(f)); }
    catch (ex) { setErr(ex.message); }
    finally { setBusy(false); if (ref.current) ref.current.value = ''; }
  }
  const lab = { fontSize: 11, fontWeight: 700, color: C.muted, display: 'block', marginBottom: 4, textTransform: 'uppercase', letterSpacing: .3 };
  const mini = (bg) => ({ background: bg || C.accent, color: '#fff', border: 'none', borderRadius: 6, padding: '5px 10px', cursor: 'pointer', fontSize: 12, fontWeight: 600 });
  return (
    <div>
      {label && <label style={lab}>{label}</label>}
      <input type="file" ref={ref} accept={accept || '.pdf,.jpg,.jpeg,.png,.webp,.doc,.docx'} style={{ display: 'none' }} onChange={pick} />
      {value ? (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13 }}>
          <a href={value} target="_blank" rel="noopener" style={{ color: C.accent, fontWeight: 600 }}>📎 Voir le document</a>
          <button style={mini(C.accent)} disabled={busy} onClick={() => ref.current && ref.current.click()}>Remplacer</button>
          <button style={mini('#64748b')} onClick={() => onChange('')}>Retirer</button>
        </div>
      ) : (
        <button style={mini()} disabled={busy} onClick={() => ref.current && ref.current.click()}>{busy ? 'Téléversement…' : '⬆ Téléverser'}</button>
      )}
      {err && <div style={{ color: '#dc2626', fontSize: 12, marginTop: 4 }}>{err}</div>}
    </div>
  );
}

// ── Section « Page d'accueil » : contenu global du site (photos, textes,
// étiquette, chiffres). Indépendant des programmes ; stocké via /api/site-admin/
// home-content. Tant qu'un champ reste vide, l'accueil garde son texte par défaut.
const HOME_FIELDS = ['heroEyebrow', 'heroTitle', 'heroText', 'heroCaptionTitle', 'heroCaptionSub',
  'heroPhotoUrl', 'blueTitle', 'blueText1', 'blueText2', 'bluePhotoUrl',
  'stat1Value', 'stat1Label', 'stat2Value', 'stat2Label', 'stat3Value', 'stat3Label'];

function HomeContentSection({ C }) {
  const blank = Object.fromEntries(HOME_FIELDS.map(k => [k, '']));
  const [form, setForm]   = React.useState(blank);
  const [open, setOpen]   = React.useState(false);
  const [busy, setBusy]   = React.useState(false);
  const [msg, setMsg]     = React.useState('');

  React.useEffect(() => {
    fetch('/api/site-admin/home-content')
      .then(r => r.json()).then(d => {
        const c = (d && d.content) || {};
        setForm({ ...blank, ...Object.fromEntries(HOME_FIELDS.map(k => [k, c[k] != null ? String(c[k]) : ''])) });
      }).catch(() => {});
  }, []);

  const set = (k, v) => setForm(s => ({ ...s, [k]: v }));
  function flash(t) { setMsg(t); setTimeout(() => setMsg(''), 3000); }

  async function save() {
    setBusy(true);
    try {
      const r = await fetch('/api/site-admin/home-content', {
        method: 'PUT', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ fields: form }),
      });
      if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || 'Erreur ' + r.status);
      flash('✓ Page d\'accueil enregistrée');
    } catch (e) { flash('✗ ' + e.message); } finally { setBusy(false); }
  }

  const card  = { background: C.card, border: '1px solid ' + C.border, borderRadius: 10, padding: 16, marginBottom: 14 };
  const label = { fontSize: 11, fontWeight: 700, color: C.muted, display: 'block', marginBottom: 4, textTransform: 'uppercase', letterSpacing: .3 };
  const input = { width: '100%', padding: '7px 9px', border: '1px solid ' + C.border, borderRadius: 7, fontSize: 13, boxSizing: 'border-box', background: C.card, color: C.text };
  const btn   = (bg) => ({ background: bg || C.accent, color: '#fff', border: 'none', borderRadius: 7, padding: '8px 16px', cursor: 'pointer', fontSize: 13, fontWeight: 600 });
  const sub   = { fontSize: 13, fontWeight: 700, margin: '4px 0 10px', color: C.text };
  const txt   = (k, ph, multiline) => multiline
    ? <textarea style={{ ...input, minHeight: 70, resize: 'vertical', fontFamily: 'inherit' }} placeholder={ph} value={form[k]} onChange={e => set(k, e.target.value)} />
    : <input style={input} placeholder={ph} value={form[k]} onChange={e => set(k, e.target.value)} />;

  return (
    <div style={{ ...card, borderColor: C.accent }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }} onClick={() => setOpen(o => !o)}>
        <span style={{ fontSize: 15, fontWeight: 700 }}>🏠 Page d'accueil</span>
        <span style={{ fontSize: 12, color: C.muted }}>Photos, textes et chiffres de la page d'accueil du site.</span>
        <span style={{ marginLeft: 'auto', fontSize: 13, color: C.accent, fontWeight: 700 }}>{open ? '▾ Replier' : '▸ Modifier'}</span>
      </div>

      {open && (
        <div style={{ marginTop: 14 }}>
          {msg && <div style={{ marginBottom: 12, padding: '8px 12px', borderRadius: 8, fontSize: 13, fontWeight: 600,
            background: msg[0] === '✓' ? '#dcfce7' : '#fee2e2', color: msg[0] === '✓' ? '#15803d' : '#dc2626' }}>{msg}</div>}
          <div style={{ fontSize: 11, color: C.muted, marginBottom: 14 }}>Astuce&nbsp;: laisse un champ vide pour garder le texte (ou le visuel) par défaut.</div>

          {/* Bandeau d'accueil */}
          <div style={sub}>Bandeau d'accueil (haut de page)</div>
          <div style={{ marginBottom: 10 }}><label style={label}>Petite étiquette (au-dessus du titre)</label>{txt('heroEyebrow', 'Promotion immobilière · Économie Bleue')}</div>
          <div style={{ marginBottom: 10 }}><label style={label}>Titre principal</label>{txt('heroTitle', 'L\'investissement écologique & social…')}</div>
          <div style={{ marginBottom: 10 }}><label style={label}>Paragraphe d'accroche</label>{txt('heroText', 'Blue marie écologie, social et rentabilité…', true)}<FormatHint C={C} /></div>
          <div style={{ marginBottom: 12 }}>
            <SiteDocField C={C} label="Photo du bandeau" accept=".jpg,.jpeg,.png,.webp" value={form.heroPhotoUrl} onChange={u => set('heroPhotoUrl', u)} />
          </div>
          <div style={{ display: 'flex', gap: 18, flexWrap: 'wrap', marginBottom: 16 }}>
            <div style={{ flex: '1 1 180px' }}><label style={label}>Étiquette photo — titre</label>{txt('heroCaptionTitle', 'Cœur de ville')}</div>
            <div style={{ flex: '1 1 220px' }}><label style={label}>Étiquette photo — légende</label>{txt('heroCaptionSub', 'Rénovation écologique & sociale')}</div>
          </div>

          {/* Section « Blue, c'est quoi ? » */}
          <div style={sub}>Section « Blue, c'est quoi ? »</div>
          <div style={{ marginBottom: 10 }}><label style={label}>Titre</label>{txt('blueTitle', 'Une nouvelle façon de voir…')}</div>
          <div style={{ marginBottom: 10 }}><label style={label}>Paragraphe 1</label>{txt('blueText1', 'Blue met en œuvre l\'économie Bleue…', true)}<FormatHint C={C} /></div>
          <div style={{ marginBottom: 10 }}><label style={label}>Paragraphe 2</label>{txt('blueText2', 'Nous tournons le dos aux programmes…', true)}<FormatHint C={C} /></div>
          <div style={{ marginBottom: 16 }}>
            <SiteDocField C={C} label="Photo de la section" accept=".jpg,.jpeg,.png,.webp" value={form.bluePhotoUrl} onChange={u => set('bluePhotoUrl', u)} />
          </div>

          {/* Chiffres */}
          <div style={sub}>Les 3 chiffres</div>
          {[1, 2, 3].map(n => (
            <div key={n} style={{ display: 'flex', gap: 14, flexWrap: 'wrap', marginBottom: 10, alignItems: 'flex-end' }}>
              <div style={{ flex: '0 0 140px' }}><label style={label}>Chiffre {n}</label>{txt('stat' + n + 'Value', n === 1 ? '120+' : n === 2 ? '1,2M' : '100 %')}</div>
              <div style={{ flex: '1 1 240px' }}><label style={label}>Libellé {n}</label>{txt('stat' + n + 'Label', n === 1 ? 'logements rénovés' : n === 2 ? 'kWh économisés / an' : 'en cœur de ville')}</div>
            </div>
          ))}

          <button style={{ ...btn(), marginTop: 8 }} disabled={busy} onClick={save}>{busy ? 'Enregistrement…' : 'Enregistrer la page d\'accueil'}</button>
        </div>
      )}
    </div>
  );
}

function ContenuSiteView({ C, projects, fiches }) {
  const [selProg, setSelProg]   = React.useState('');
  const [progForm, setProgForm] = React.useState({ heroPhotoUrl: '', presentationTexte: '', atoutsQuartier: '', livraison: '', plaquetteUrl: '',
    pitch: '', intro: '', population: '', populationNote: '', priceRange: '', priceNote: '', marketNote: '',
    adresseLignes: '', caracteristiques: '', building: '', detailPhoto1Url: '', detailPhoto2Url: '', bandeauPhotoUrl: '' });
  const [lotForms, setLotForms] = React.useState({});
  const [busy, setBusy]         = React.useState('');
  const [msg, setMsg]           = React.useState('');
  const photoRef = React.useRef(null);

  const fiche = selProg ? (fiches[selProg] || {}) : null;
  const lots  = fiche && Array.isArray(fiche.lots) ? fiche.lots : [];
  const isPublic = fiche && (fiche.statut === 'En cours' || fiche.statut === 'Livré');

  React.useEffect(() => {
    if (!selProg) return;
    const f = fiches[selProg] || {};
    setProgForm({ heroPhotoUrl: f.heroPhotoUrl || '', presentationTexte: f.presentationTexte || '', atoutsQuartier: f.atoutsQuartier || '', livraison: f.livraison || '', plaquetteUrl: f.plaquetteUrl || '',
      pitch: f.pitch || '', intro: f.intro || '', population: f.population || '', populationNote: f.populationNote || '', priceRange: f.priceRange || '', priceNote: f.priceNote || '', marketNote: f.marketNote || '',
      adresseLignes: f.adresseLignes || '', caracteristiques: f.caracteristiques || '', building: f.building || '', detailPhoto1Url: f.detailPhoto1Url || '', detailPhoto2Url: f.detailPhoto2Url || '', bandeauPhotoUrl: f.bandeauPhotoUrl || '' });
    const lf = {};
    (f.lots || []).forEach((lot, i) => {
      lf[i] = {
        prixSite:             (lot.prixSite === 0 || lot.prixSite) ? String(lot.prixSite) : '',
        dpeActuel:            lot.dpeActuel || '',
        dpeProjete:           lot.dpeProjete || '',
        dpeActuelDocUrl:      lot.dpeActuelDocUrl || '',
        dpeProjeteDocUrl:     lot.dpeProjeteDocUrl || '',
        descriptifTravaux:    lot.descriptifTravaux || '',
        descriptifTravauxUrl: lot.descriptifTravauxUrl || '',
        planUrl:              lot.planUrl || '',
        attestationUrl:       lot.attestationUrl || '',
        photos:               (Array.isArray(lot.photos) ? lot.photos.map(p => (typeof p === 'string' ? { url: p } : p)).filter(p => p && p.url) : []),
      };
    });
    setLotForms(lf);
    setMsg('');
    // Dépend UNIQUEMENT de selProg (pas de `fiches`) : le formulaire se (re)charge
    // au changement de programme, mais PAS à chaque rafraîchissement SSE de `fiches`
    // — sinon la saisie en cours serait écrasée (dette D6). On accepte de ne pas
    // refléter une modif externe du même programme tant qu'on ne le ressélectionne pas.
  }, [selProg]);

  function flash(t) { setMsg(t); setTimeout(() => setMsg(''), 3000); }
  const setLF = (idx, k, v) => setLotForms(s => ({ ...s, [idx]: { ...(s[idx] || {}), [k]: v } }));

  async function saveProg() {
    setBusy('prog');
    try {
      const r = await fetch('/api/site-admin/programme-content', {
        method: 'PUT', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ programmeId: selProg, fields: progForm }),
      });
      if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || 'Erreur ' + r.status);
      flash('✓ Présentation du programme enregistrée');
    } catch (e) { flash('✗ ' + e.message); } finally { setBusy(''); }
  }

  async function saveLot(idx) {
    setBusy('lot:' + idx);
    const lf = lotForms[idx] || {};
    try {
      const r = await fetch('/api/site-admin/lot-content', {
        method: 'PUT', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ programmeId: selProg, lotIdx: idx, fields: {
          prixSite: lf.prixSite,
          dpeActuel: lf.dpeActuel, dpeProjete: lf.dpeProjete,
          dpeActuelDocUrl: lf.dpeActuelDocUrl, dpeProjeteDocUrl: lf.dpeProjeteDocUrl,
          descriptifTravaux: lf.descriptifTravaux, descriptifTravauxUrl: lf.descriptifTravauxUrl,
          planUrl: lf.planUrl, attestationUrl: lf.attestationUrl,
          photos: (lf.photos || []).map(p => p.url),
        } }),
      });
      if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || 'Erreur ' + r.status);
      flash('✓ Lot ' + (idx + 1) + ' enregistré');
    } catch (e) { flash('✗ ' + e.message); } finally { setBusy(''); }
  }

  async function addPhotos(idx, fileList) {
    const files = Array.from(fileList || []);
    if (!files.length) return;
    setBusy('photos:' + idx);
    try {
      const urls = [];
      for (const f of files) urls.push({ url: await uploadSiteFile(f) });
      setLF(idx, 'photos', [ ...((lotForms[idx] || {}).photos || []), ...urls ]);
    } catch (e) { flash('✗ ' + e.message); } finally { setBusy(''); }
  }
  const removePhoto = (idx, i) => setLF(idx, 'photos', ((lotForms[idx] || {}).photos || []).filter((_, j) => j !== i));

  // ── Styles ──
  const card  = { background: C.card, border: '1px solid ' + C.border, borderRadius: 10, padding: 16, marginBottom: 14 };
  const label = { fontSize: 11, fontWeight: 700, color: C.muted, display: 'block', marginBottom: 4, textTransform: 'uppercase', letterSpacing: .3 };
  const input = { width: '100%', padding: '7px 9px', border: '1px solid ' + C.border, borderRadius: 7, fontSize: 13, boxSizing: 'border-box', background: C.card, color: C.text };
  const btn   = (bg) => ({ background: bg || C.accent, color: '#fff', border: 'none', borderRadius: 7, padding: '8px 16px', cursor: 'pointer', fontSize: 13, fontWeight: 600 });
  const dpeBox = { ...input, width: 90 };

  return (
    <div style={{ padding: '18px 20px', maxWidth: 1100, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
        <h2 style={{ margin: 0, fontSize: 18 }}>🌐 Contenu site</h2>
        <span style={{ fontSize: 12, color: C.muted }}>Édite ce qui s'affiche sur le site public. Les documents se téléversent ici — ils sont stockés sur ton serveur, rien à voir avec OneDrive.</span>
      </div>

      <HomeContentSection C={C} />

      <div style={{ marginBottom: 16 }}>
        <label style={label}>Programme</label>
        <select value={selProg} onChange={e => setSelProg(e.target.value)} style={{ ...input, maxWidth: 420 }}>
          <option value="">— Choisir un programme —</option>
          <GroupedProgrammeOptions projects={projects} fiches={fiches} />
        </select>
      </div>

      {msg && <div style={{ position: 'sticky', top: 8, zIndex: 5, marginBottom: 12, padding: '8px 12px', borderRadius: 8, fontSize: 13, fontWeight: 600,
        background: msg[0] === '✓' ? '#dcfce7' : '#fee2e2', color: msg[0] === '✓' ? '#15803d' : '#dc2626' }}>{msg}</div>}

      {!selProg && <div style={{ color: C.muted, fontSize: 14, padding: 40, textAlign: 'center' }}>Sélectionne un programme pour éditer son contenu public.</div>}

      {selProg && (
        <div>
          {!isPublic && (
            <div style={{ ...card, background: '#fef3c7', borderColor: '#fcd34d', color: '#92400e', fontSize: 13 }}>
              ⚠️ Ce programme n'est pas « En cours » ni « Livré » : il <b>n'apparaît pas</b> sur le site public. Tu peux quand même préparer son contenu.
            </div>
          )}

          {/* Présentation programme */}
          <div style={card}>
            <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 12 }}>Présentation du programme</div>
            <div style={{ marginBottom: 12 }}>
              <SiteDocField C={C} label="Photo d'accueil" accept=".jpg,.jpeg,.png,.webp" value={progForm.heroPhotoUrl} onChange={u => setProgForm(s => ({ ...s, heroPhotoUrl: u }))} />
            </div>
            <div style={{ marginBottom: 12 }}>
              <label style={label}>Texte de présentation</label>
              <textarea style={{ ...input, minHeight: 90, resize: 'vertical', fontFamily: 'inherit' }} value={progForm.presentationTexte}
                onChange={e => setProgForm(s => ({ ...s, presentationTexte: e.target.value }))} />
              <FormatHint C={C} />
            </div>
            <div style={{ marginBottom: 12 }}>
              <label style={label}>Atouts du quartier</label>
              <textarea style={{ ...input, minHeight: 70, resize: 'vertical', fontFamily: 'inherit' }} value={progForm.atoutsQuartier}
                placeholder="Proximité transports, commerces, écoles… (s'affiche sur l'Espace CGP, sous la présentation)"
                onChange={e => setProgForm(s => ({ ...s, atoutsQuartier: e.target.value }))} />
              <FormatHint C={C} />
            </div>
            <div style={{ marginBottom: 12 }}>
              <label style={label}>Livraison (affichée sur l'accueil)</label>
              <input style={{ ...input, maxWidth: 220 }} value={progForm.livraison}
                placeholder="ex. T3 2026"
                onChange={e => setProgForm(s => ({ ...s, livraison: e.target.value }))} />
            </div>
            <div style={{ marginBottom: 12 }}>
              <SiteDocField C={C} label="Plaquette du programme" value={progForm.plaquetteUrl} onChange={u => setProgForm(s => ({ ...s, plaquetteUrl: u }))} />
            </div>

            {/* ── Fiche programme détaillée (page « Découvrir le programme ») ── */}
            <div style={{ borderTop: '1px solid ' + C.border, margin: '18px 0 14px', paddingTop: 14 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: C.text }}>Fiche détaillée du programme</div>
              <div style={{ fontSize: 11, color: C.muted, marginTop: 3 }}>S'affiche sur la page « Découvrir le programme ». Laisse un champ vide pour masquer la section correspondante.</div>
            </div>
            <div style={{ marginBottom: 12 }}>
              <SiteDocField C={C} label="Photo du bandeau (page détaillée)" accept=".jpg,.jpeg,.png,.webp" value={progForm.bandeauPhotoUrl} onChange={u => setProgForm(s => ({ ...s, bandeauPhotoUrl: u }))} />
              <div style={{ fontSize: 11, color: C.muted, marginTop: 4 }}>Grande photo en haut de la page détaillée. Si vide, la « Photo d'accueil » ci-dessus est réutilisée.</div>
            </div>
            <div style={{ marginBottom: 12 }}>
              <label style={label}>Accroche (en-tête)</label>
              <textarea style={{ ...input, minHeight: 60, resize: 'vertical', fontFamily: 'inherit' }} value={progForm.pitch}
                placeholder="Phrase d'accroche affichée en haut de la fiche."
                onChange={e => setProgForm(s => ({ ...s, pitch: e.target.value }))} />
              <FormatHint C={C} />
            </div>
            <div style={{ marginBottom: 12 }}>
              <label style={label}>Texte d'introduction</label>
              <textarea style={{ ...input, minHeight: 90, resize: 'vertical', fontFamily: 'inherit' }} value={progForm.intro}
                placeholder="Présentation de la ville / du contexte. Sautez une ligne pour séparer les paragraphes."
                onChange={e => setProgForm(s => ({ ...s, intro: e.target.value }))} />
              <FormatHint C={C} />
            </div>

            <div style={{ fontSize: 12, fontWeight: 700, color: C.muted, margin: '6px 0 8px', textTransform: 'uppercase', letterSpacing: .3 }}>Le marché local</div>
            <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', marginBottom: 10 }}>
              <div style={{ flex: '1 1 140px' }}><label style={label}>Population (chiffre)</label><input style={input} value={progForm.population} placeholder="≈ 16 000" onChange={e => setProgForm(s => ({ ...s, population: e.target.value }))} /></div>
              <div style={{ flex: '1 1 180px' }}><label style={label}>Population (légende)</label><input style={input} value={progForm.populationNote} placeholder="habitants" onChange={e => setProgForm(s => ({ ...s, populationNote: e.target.value }))} /></div>
            </div>
            <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', marginBottom: 10 }}>
              <div style={{ flex: '1 1 140px' }}><label style={label}>Prix au m² (fourchette)</label><input style={input} value={progForm.priceRange} placeholder="2 000 – 3 200 €" onChange={e => setProgForm(s => ({ ...s, priceRange: e.target.value }))} /></div>
              <div style={{ flex: '1 1 180px' }}><label style={label}>Prix au m² (légende)</label><input style={input} value={progForm.priceNote} placeholder="au m² dans l'ancien rénové" onChange={e => setProgForm(s => ({ ...s, priceNote: e.target.value }))} /></div>
            </div>
            <div style={{ marginBottom: 12 }}>
              <label style={label}>Texte sur le marché</label>
              <textarea style={{ ...input, minHeight: 70, resize: 'vertical', fontFamily: 'inherit' }} value={progForm.marketNote}
                placeholder="Quelques lignes sur le marché locatif / immobilier local."
                onChange={e => setProgForm(s => ({ ...s, marketNote: e.target.value }))} />
              <FormatHint C={C} />
            </div>

            <div style={{ fontSize: 12, fontWeight: 700, color: C.muted, margin: '6px 0 8px', textTransform: 'uppercase', letterSpacing: .3 }}>Notre programme</div>
            <div style={{ display: 'flex', gap: 18, flexWrap: 'wrap', marginBottom: 10 }}>
              <div style={{ flex: '1 1 220px' }}>
                <label style={label}>Localisation (une ligne par ligne)</label>
                <textarea style={{ ...input, minHeight: 60, resize: 'vertical', fontFamily: 'inherit' }} value={progForm.adresseLignes}
                  placeholder={"Centre-ville de Tarascon\n13150 Tarascon"}
                  onChange={e => setProgForm(s => ({ ...s, adresseLignes: e.target.value }))} />
              </div>
              <div style={{ flex: '1 1 220px' }}>
                <label style={label}>Caractéristiques (une ligne par ligne)</label>
                <textarea style={{ ...input, minHeight: 60, resize: 'vertical', fontFamily: 'inherit' }} value={progForm.caracteristiques}
                  placeholder={"2 T2 rénovés\n1 T3 rénové\n1 T4 rénové"}
                  onChange={e => setProgForm(s => ({ ...s, caracteristiques: e.target.value }))} />
              </div>
            </div>
            <div style={{ fontSize: 11, color: C.muted, marginBottom: 12 }}>La « Livraison » affichée ici reprend le champ « Livraison » ci-dessus.</div>
            <div style={{ marginBottom: 12 }}>
              <label style={label}>Descriptif du programme</label>
              <textarea style={{ ...input, minHeight: 90, resize: 'vertical', fontFamily: 'inherit' }} value={progForm.building}
                placeholder="Description de l'immeuble et des travaux. Sautez une ligne pour séparer les paragraphes."
                onChange={e => setProgForm(s => ({ ...s, building: e.target.value }))} />
              <FormatHint C={C} />
            </div>
            <div style={{ display: 'flex', gap: 28, flexWrap: 'wrap', marginBottom: 16 }}>
              <SiteDocField C={C} label="Photo programme 1" accept=".jpg,.jpeg,.png,.webp" value={progForm.detailPhoto1Url} onChange={u => setProgForm(s => ({ ...s, detailPhoto1Url: u }))} />
              <SiteDocField C={C} label="Photo programme 2" accept=".jpg,.jpeg,.png,.webp" value={progForm.detailPhoto2Url} onChange={u => setProgForm(s => ({ ...s, detailPhoto2Url: u }))} />
            </div>

            <button style={btn()} disabled={busy === 'prog'} onClick={saveProg}>{busy === 'prog' ? 'Enregistrement…' : 'Enregistrer la présentation'}</button>
          </div>

          {/* Lots */}
          <div style={{ fontSize: 14, fontWeight: 700, margin: '18px 0 10px' }}>Lots ({lots.length})</div>
          {lots.map((lot, idx) => {
            const lf = lotForms[idx] || {};
            return (
              <div key={idx} style={card}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
                  <span style={{ fontWeight: 700, fontSize: 14 }}>Lot {idx + 1}</span>
                  <span style={{ fontSize: 12, color: C.muted }}>{lot.type || '—'} · {lot.surface || '—'} m²</span>
                  <span style={{ marginLeft: 'auto', fontSize: 11, color: C.muted }}>statut : {lot.statutCommercial || 'LIBRE'}</span>
                </div>

                {/* Prix affiché sur le site (vitrine) */}
                <div style={{ marginBottom: 12 }}>
                  <label style={label}>Prix affiché sur le site (€)</label>
                  <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
                    <input type="number" min="0" step="1000" style={{ ...input, width: 180 }}
                      placeholder="prix de vente public"
                      value={lf.prixSite || ''} onChange={e => setLF(idx, 'prixSite', e.target.value)} />
                    <span style={{ fontSize: 11, color: C.muted }}>Laisser vide&nbsp;= le site affiche le prix de vente calculé.</span>
                  </div>
                </div>

                {/* DPE : lettre + document */}
                <div style={{ display: 'flex', gap: 24, flexWrap: 'wrap', marginBottom: 12 }}>
                  <div>
                    <label style={label}>DPE actuel</label>
                    <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                      <select style={dpeBox} value={lf.dpeActuel || ''} onChange={e => setLF(idx, 'dpeActuel', e.target.value)}>
                        {['', 'A', 'B', 'C', 'D', 'E', 'F', 'G'].map(v => <option key={v} value={v}>{v || '—'}</option>)}
                      </select>
                      <SiteDocField C={C} accept=".pdf,.jpg,.jpeg,.png" value={lf.dpeActuelDocUrl} onChange={u => setLF(idx, 'dpeActuelDocUrl', u)} />
                    </div>
                  </div>
                  <div>
                    <label style={label}>DPE projeté</label>
                    <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                      <select style={dpeBox} value={lf.dpeProjete || ''} onChange={e => setLF(idx, 'dpeProjete', e.target.value)}>
                        {['', 'A', 'B', 'C', 'D', 'E', 'F', 'G'].map(v => <option key={v} value={v}>{v || '—'}</option>)}
                      </select>
                      <SiteDocField C={C} accept=".pdf,.jpg,.jpeg,.png" value={lf.dpeProjeteDocUrl} onChange={u => setLF(idx, 'dpeProjeteDocUrl', u)} />
                    </div>
                  </div>
                </div>

                {/* Descriptif : texte court + document */}
                <div style={{ marginBottom: 10 }}>
                  <label style={label}>Descriptif des travaux (texte court, optionnel)</label>
                  <textarea style={{ ...input, minHeight: 60, resize: 'vertical', fontFamily: 'inherit' }} value={lf.descriptifTravaux || ''}
                    onChange={e => setLF(idx, 'descriptifTravaux', e.target.value)} />
                </div>
                <div style={{ marginBottom: 12 }}>
                  <SiteDocField C={C} label="Descriptif des travaux (document)" value={lf.descriptifTravauxUrl} onChange={u => setLF(idx, 'descriptifTravauxUrl', u)} />
                </div>

                {/* Plan + attestation */}
                <div style={{ display: 'flex', gap: 28, flexWrap: 'wrap', marginBottom: 12 }}>
                  <SiteDocField C={C} label="Plan du lot" accept=".pdf,.jpg,.jpeg,.png" value={lf.planUrl} onChange={u => setLF(idx, 'planUrl', u)} />
                  <SiteDocField C={C} label="Attestation avocat" value={lf.attestationUrl} onChange={u => setLF(idx, 'attestationUrl', u)} />
                </div>

                {/* Photos */}
                <div style={{ marginBottom: 12 }}>
                  <label style={label}>Photos</label>
                  <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 8 }}>
                    {(lf.photos || []).map((p, i) => (
                      <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: C.bg, border: '1px solid ' + C.border, borderRadius: 6, padding: '4px 8px', fontSize: 12 }}>
                        <a href={p.url} target="_blank" rel="noopener" style={{ color: C.accent }}>photo {i + 1}</a>
                        <button onClick={() => removePhoto(idx, i)} style={{ background: 'none', border: 'none', color: '#dc2626', cursor: 'pointer', fontWeight: 700 }}>×</button>
                      </span>
                    ))}
                    {(!lf.photos || !lf.photos.length) && <span style={{ fontSize: 12, color: C.muted }}>Aucune photo.</span>}
                  </div>
                  <input type="file" accept=".jpg,.jpeg,.png,.webp" multiple style={{ display: 'none' }}
                    ref={el => { if (el) el.dataset.idx = idx; }} id={'ph-' + idx} onChange={e => addPhotos(idx, e.target.files)} />
                  <button style={btn('#64748b')} disabled={busy === 'photos:' + idx} onClick={() => document.getElementById('ph-' + idx).click()}>
                    {busy === 'photos:' + idx ? 'Téléversement…' : '⬆ Ajouter des photos'}
                  </button>
                </div>

                <button style={btn()} disabled={busy === 'lot:' + idx} onClick={() => saveLot(idx)}>{busy === 'lot:' + idx ? 'Enregistrement…' : 'Enregistrer le lot ' + (idx + 1)}</button>
              </div>
            );
          })}
          {lots.length === 0 && <div style={{ color: C.muted, fontSize: 13 }}>Ce programme n'a pas encore de lots.</div>}
        </div>
      )}
    </div>
  );
}
