// InstantDevis — Profil Artisan (Module Légal) + onglet Fiscal (préréglages)

const _AF_FISCAL_VAT_OPTIONS = [
  { value: 'franchise', label: 'Franchise en base (micro, pas de TVA refacturée en plus)' },
  { value: 'reel_simplifie', label: 'Réel simplifié' },
  { value: 'reel_normal', label: 'Réel normal' },
  { value: 'assujetti', label: 'Assujetti TVA (société, TVA sur factures)' },
];

const _AF_FISCAL_CUSTOMER_OPTIONS = [
  { value: 'particuliers', label: 'Particuliers' },
  { value: 'professionnels', label: 'Professionnels (B2B)' },
  { value: 'mixte', label: 'Mixte' },
];

const _AF_FISCAL_TRADE_OPTIONS = [
  { value: 'plomberie', label: 'Plomberie' },
  { value: 'electricite', label: 'Électricité' },
  { value: 'peinture', label: 'Peinture' },
  { value: 'multi', label: 'Plusieurs corps de métier' },
];

const _FISCAL_EDIT_KEYS = new Set([
  'legalForm', 'vatMode', 'customerMode', 'primaryTrade', 'defaultTva', 'acomptePercent', 'fiscalMentionShort',
]);

function AfProfileField({ label, value, onChange, t, placeholder, type = 'text', required, hint, mono }) {
  const [focused, setFocused] = React.useState(false);
  return (
    <div>
      <label style={{ fontSize: 11, fontWeight: 700, color: t.textMuted, textTransform: 'uppercase', letterSpacing: 0.6, display: 'flex', alignItems: 'center', gap: 4, marginBottom: 6 }}>
        {label}{required && <span style={{ color: t.safety }}>*</span>}
      </label>
      <input
        type={type} value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder}
        onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}
        style={{
          width: '100%', padding: '11px 14px', borderRadius: 8,
          background: t.bgElevated,
          border: `1.5px solid ${focused ? t.safety : value ? t.primary + '55' : t.border}`,
          fontSize: 14, fontWeight: mono ? 700 : 500,
          fontFamily: mono ? 'monospace' : 'inherit',
          color: t.text, outline: 'none', transition: 'border-color 0.2s',
        }}
      />
      {hint && <div style={{ fontSize: 10, color: t.textMuted, marginTop: 4, fontWeight: 600 }}>{hint}</div>}
    </div>
  );
}

function AfProfileSelect({ label, value, onChange, t, options, required }) {
  const [focused, setFocused] = React.useState(false);
  return (
    <div>
      <label style={{ fontSize: 11, fontWeight: 700, color: t.textMuted, textTransform: 'uppercase', letterSpacing: 0.6, display: 'block', marginBottom: 6 }}>
        {label}{required && <span style={{ color: t.safety }}> *</span>}
      </label>
      <select
        value={value}
        onChange={e => onChange(e.target.value)}
        onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}
        style={{
          width: '100%', padding: '11px 14px', borderRadius: 8,
          background: t.bgElevated,
          border: `1.5px solid ${focused ? t.safety : value ? t.primary + '55' : t.border}`,
          fontSize: 14, fontWeight: 500, color: t.text, outline: 'none', cursor: 'pointer',
        }}
      >
        {options.map(o => (
          <option key={o.value} value={o.value}>{o.label}</option>
        ))}
      </select>
    </div>
  );
}

function AfProfile({ t, onBack }) {
  const [form, setForm] = React.useState(() => {
    const p = { ...AF_PROFILE_STORE.get() };
    if ('openAiKey' in p) try { delete p.openAiKey; } catch (e) {}
    return p;
  });
  const [saved, setSaved] = React.useState(false);
  const [section, setSection] = React.useState('identity');

  const update = (k, v) => {
    setForm((f) => {
      const next = { ...f, [k]: v };
      if (_FISCAL_EDIT_KEYS.has(k)) {
        next.fiscalCustomized = true;
      }
      return next;
    });
    setSaved(false);
  };

  const applyPreset = (presetId) => {
    if (typeof AF_FISCAL === 'undefined') return;
    const patch = AF_FISCAL.buildApplyPresetPatch(presetId);
    if (!patch) return;
    setForm(f => ({ ...f, ...patch }));
    setSaved(false);
  };

  const handleSave = () => {
    if (typeof AF_STORE !== 'undefined' && AF_STORE.saveProfile) {
      AF_STORE.saveProfile(form);
    } else {
      AF_PROFILE_STORE.save(form);
    }
    setSaved(true);
    setTimeout(() => setSaved(false), 2500);
  };

  const completeness = (() => {
    const fields = [form.nom, form.siret, form.adresse, form.assuranceNum, form.iban];
    return Math.round((fields.filter(f => f && f.trim()).length / fields.length) * 100);
  })();

  const fiscalStatusLine = (() => {
    const pr = form.companyPreset || 'custom';
    if (pr === 'custom') {
      return 'Mode manuel : paramètres saisis librement (aucun préréglage de type d’entreprise appliqué).';
    }
    const base = (typeof AF_FISCAL !== 'undefined') ? AF_FISCAL.getPresetLabel(pr) : pr;
    if (!form.fiscalCustomized) {
      return 'Préréglage actif : ' + base + '. Tous les champs restent modifiables ci-dessous.';
    }
    return 'D’après le préréglage « ' + base + ' », avec ajustements manuels (profil personnalisé).';
  })();

  const fiscalAgentReady = (typeof AF_FISCAL !== 'undefined')
    ? AF_FISCAL.isProfileComplete(form)
    : false;

  const tabs = [
    { id: 'identity', label: 'Identité' },
    { id: 'legal',    label: 'Légal'    },
    { id: 'fiscal',   label: 'Fiscal'   },
    { id: 'bank',     label: 'Bancaire' },
    { id: 'cloud',    label: 'Cloud'    },
  ];

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflowY: 'auto', background: t.bg }}>
      <AfScreenHeader title="Profil Pro" subtitle="Informations légales, fiscalité & PDF" t={t} back onBack={onBack} tape />

      {/* Progression */}
      <div style={{ padding: '12px 16px 0' }}>
        <div style={{ background: t.bgElevated, borderRadius: 10, border: `1px solid ${completeness >= 80 ? 'rgba(16,185,129,0.4)' : t.border}`, padding: '12px 14px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
            <span style={{ fontSize: 12, fontWeight: 700, color: t.text }}>Complétude du profil PDF</span>
            <span style={{ fontSize: 12, fontWeight: 800, color: completeness >= 80 ? '#10B981' : t.safety }}>{completeness}%</span>
          </div>
          <div style={{ height: 5, borderRadius: 3, background: t.bgSunken, overflow: 'hidden' }}>
            <div style={{ height: '100%', borderRadius: 3, width: `${completeness}%`, background: completeness >= 80 ? '#10B981' : t.safety, transition: 'width 0.5s' }} />
          </div>
          <div style={{ fontSize: 10, color: t.textMuted, marginTop: 5 }}>
            {completeness >= 80 ? '✅ Vos infos apparaîtront dans chaque PDF généré' : '⚠️ Complétez votre profil pour personnaliser les PDF'}
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 0, padding: '12px 16px 0', flexWrap: 'wrap' }}>
        {tabs.map((s, i) => (
          <button key={s.id} onClick={() => setSection(s.id)} style={{
            flex: 1, minWidth: 56, padding: '9px 4px',
            borderRadius: i === 0 ? '8px 0 0 8px' : i === tabs.length - 1 ? '0 8px 8px 0' : 0,
            background: section === s.id ? t.primary : t.bgElevated,
            color: section === s.id ? '#fff' : t.textMuted,
            border: `1px solid ${section === s.id ? t.primary : t.border}`,
            borderLeft: i > 0 ? 'none' : undefined,
            fontSize: 10, fontWeight: 700, cursor: 'pointer',
          }}>{s.label}</button>
        ))}
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '14px 16px 100px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {section === 'identity' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, animation: 'af-slide-up 0.2s both' }}>
            <div style={{ padding: '10px 12px', borderRadius: 8, background: 'rgba(11,61,92,0.08)', border: '1px solid rgba(11,61,92,0.22)', fontSize: 11, color: t.primary, lineHeight: 1.5 }}>
              Vos informations sont enregistrées sur cet appareil. La synchronisation multi-appareils arrivera avec le compte artisan.
            </div>
            <AfProfileField label="Nom artisan" value={form.nom} onChange={v => update('nom', v)} t={t} placeholder="Jean Dupont" required />
            <AfProfileField label="Nom entreprise" value={form.entreprise} onChange={v => update('entreprise', v)} t={t} placeholder="Dupont Plomberie SARL" />
            <AfProfileField label="Adresse" value={form.adresse} onChange={v => update('adresse', v)} t={t} placeholder="15 rue des Artisans" />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 10 }}>
              <AfProfileField label="Code postal" value={form.codePostal} onChange={v => update('codePostal', v)} t={t} placeholder="75001" type="tel" />
              <AfProfileField label="Ville" value={form.ville} onChange={v => update('ville', v)} t={t} placeholder="Paris" />
            </div>
            <AfProfileField label="Téléphone" value={form.tel} onChange={v => update('tel', v)} t={t} placeholder="06 12 34 56 78" type="tel" />
            <AfProfileField label="Email professionnel" value={form.email} onChange={v => update('email', v)} t={t} placeholder="contact@artisan.fr" type="email" />
          </div>
        )}

        {section === 'legal' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, animation: 'af-slide-up 0.2s both' }}>
            <div style={{ padding: '10px 12px', borderRadius: 8, background: 'rgba(59,130,246,0.08)', border: '1px solid rgba(59,130,246,0.25)', fontSize: 11, color: '#3B82F6' }}>
              📋 Ces infos apparaissent dans l&apos;en-tête et le pied de page de chaque PDF. TVA par défaut et acompte : onglet <strong>Fiscal</strong>.
            </div>
            <AfProfileField label="SIRET" value={form.siret} onChange={v => update('siret', v)} t={t} placeholder="123 456 789 00012" type="tel" required
              hint={`${String(form.siret || '').replace(/\D/g, '').length}/14 chiffres${String(form.siret || '').replace(/\D/g, '').length === 14 ? ' ✅' : ''}`} />
            <AfProfileField label="Assureur décennal" value={form.assureurNom} onChange={v => update('assureurNom', v)} t={t} placeholder="AXA / MAAF / Allianz…" />
            <AfProfileField label="N° police assurance" value={form.assuranceNum} onChange={v => update('assuranceNum', v)} t={t} placeholder="AXA-2026-XXXX" required
              hint="Obligatoire sur les devis bâtiment (art. L241-1)" />

            {/* Aperçu footer PDF */}
            <div style={{ background: '#f8f7f5', borderRadius: 8, border: '1px dashed #ccc', padding: '12px 14px' }}>
              <div style={{ fontSize: 10, fontWeight: 700, color: t.textMuted, marginBottom: 6, textTransform: 'uppercase' }}>Aperçu pied de page PDF</div>
              <div style={{ fontSize: 9, color: '#555', lineHeight: 1.9, fontFamily: 'monospace' }}>
                {form.nom || 'Votre nom'}{form.entreprise ? ` — ${form.entreprise}` : ''}<br/>
                {form.adresse && `${form.adresse}, `}{form.codePostal} {form.ville}<br/>
                {form.siret && `SIRET : ${form.siret}`}
                {form.assureurNom && ` | Assurance : ${form.assureurNom} N° ${form.assuranceNum}`}
              </div>
            </div>
          </div>
        )}

        {section === 'fiscal' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, animation: 'af-slide-up 0.2s both' }}>
            <div style={{ padding: '10px 12px', borderRadius: 8, background: 'rgba(16,185,129,0.08)', border: '1px solid rgba(16,185,129,0.3)', fontSize: 11, color: '#059669', lineHeight: 1.5 }}>
              {fiscalStatusLine}
            </div>

            {!fiscalAgentReady && (
              <div style={{ padding: '10px 12px', borderRadius: 8, background: 'rgba(245,158,11,0.1)', border: '1px solid rgba(245,158,11,0.35)', fontSize: 11, color: '#B45309', lineHeight: 1.5 }}>
                <strong>Conseil :</strong> indiquez forme, TVA, clientèle et métier pour que les futurs outils (ex. contrôle fiscal) disposent d&apos;un contexte fiable. Aucun calcul automatique n&apos;est imposé ici.
              </div>
            )}

            {typeof AF_FISCAL !== 'undefined' && (
              <div>
                <label style={{ fontSize: 11, fontWeight: 700, color: t.textMuted, textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Type d&apos;entreprise — préréglage</label>
                <select
                  value={form.companyPreset || 'custom'}
                  onChange={e => applyPreset(e.target.value)}
                  style={{
                    width: '100%', padding: '12px 14px', borderRadius: 8, background: t.bgElevated,
                    border: `1.5px solid ${t.primary}55`, fontSize: 14, fontWeight: 600, color: t.text, cursor: 'pointer',
                  }}
                >
                  {AF_FISCAL.listPresets().map(p => (
                    <option key={p.id} value={p.id}>{p.label}</option>
                  ))}
                </select>
                <div style={{ fontSize: 10, color: t.textMuted, marginTop: 4, fontWeight: 600 }}>
                  Les valeurs proposées sont des points de départ pour artisans BTP — vérifiez toujours avec votre expert-comptable.
                </div>
              </div>
            )}

            <AfProfileField
              label="Forme juridique / type (texte affiché)"
              value={form.legalForm || ''}
              onChange={v => update('legalForm', v)}
              t={t}
              placeholder="ex. EURL, micro-entrepreneur…"
            />

            <AfProfileSelect
              label="Régime TVA (sélection)"
              value={form.vatMode || ''}
              onChange={v => update('vatMode', v)}
              t={t}
              required
              options={[
                { value: '', label: '— Choisir —' },
                ..._AF_FISCAL_VAT_OPTIONS,
              ]}
            />

            <AfProfileSelect
              label="Corps de métier principal"
              value={form.primaryTrade || 'multi'}
              onChange={v => update('primaryTrade', v)}
              t={t}
              options={_AF_FISCAL_TRADE_OPTIONS}
            />

            <AfProfileSelect
              label="Clientèle principale"
              value={form.customerMode || ''}
              onChange={v => update('customerMode', v)}
              t={t}
              required
              options={[
                { value: '', label: '— Choisir —' },
                ..._AF_FISCAL_CUSTOMER_OPTIONS,
              ]}
            />

            <div>
              <label style={{ fontSize: 11, fontWeight: 700, color: t.textMuted, textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Taux de TVA par défaut (lignes / catalogue)</label>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {[0, 5.5, 10, 20].map(r => (
                  <button key={r} type="button" onClick={() => update('defaultTva', r)} style={{
                    flex: 1, minWidth: 40, padding: '10px 0', borderRadius: 8, cursor: 'pointer', fontWeight: 700, fontSize: 13,
                    background: form.defaultTva === r ? t.primary : t.bgElevated,
                    color: form.defaultTva === r ? '#fff' : t.text,
                    border: `1.5px solid ${form.defaultTva === r ? t.primary : t.border}`,
                  }}>{r}%</button>
                ))}
              </div>
              <div style={{ fontSize: 10, color: t.textMuted, marginTop: 4, fontWeight: 600 }}>
                0 % = travaux exonérés / cas particuliers (à valider). Sinon 5,5 / 10 / 20 % selon travaux.
              </div>
            </div>

            <div>
              <label style={{ fontSize: 11, fontWeight: 700, color: t.textMuted, textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Acompte à la commande (par défaut)</label>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {[0, 10, 20, 30, 40, 50].map(r => (
                  <button key={r} type="button" onClick={() => update('acomptePercent', r)} style={{
                    flex: 1, minWidth: 36, padding: '10px 0', borderRadius: 8, cursor: 'pointer', fontWeight: 700, fontSize: 12,
                    background: (form.acomptePercent ?? 30) === r ? t.safety : t.bgElevated,
                    color: (form.acomptePercent ?? 30) === r ? '#fff' : t.text,
                    border: `1.5px solid ${(form.acomptePercent ?? 30) === r ? t.safety : t.border}`,
                  }}>{r}%</button>
                ))}
              </div>
              <div style={{ fontSize: 10, color: t.textMuted, marginTop: 4, fontWeight: 600 }}>
                Utilisé partout (devis, PDF, calculs) via le profil.
              </div>
            </div>

            <AfProfileField
              label="Mention courte (pied de PDF, optionnel)"
              value={form.fiscalMentionShort || ''}
              onChange={v => update('fiscalMentionShort', v)}
              t={t}
              placeholder="ex. TVA non applicable, art. 293 B — ou une ligne d’ordre d’idée, à valider"
              hint="Texte bref ; ne remplace pas un avis comptable."
            />
          </div>
        )}

        {section === 'bank' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, animation: 'af-slide-up 0.2s both' }}>
            <div style={{ padding: '10px 12px', borderRadius: 8, background: 'rgba(255,107,0,0.08)', border: '1px solid rgba(255,107,0,0.3)', fontSize: 11, color: t.safety }}>
              🔒 Stocké uniquement sur votre appareil. Affiché sur le PDF pour faciliter le virement.
            </div>
            <AfProfileField label="IBAN" value={form.iban} onChange={v => update('iban', v)} t={t}
              placeholder="FR76 3000 6000 0112 3456 7890 189" hint="Affiché sur le PDF pour virement" mono />
            {form.iban && (
              <div style={{ background: t.primary, borderRadius: 10, padding: '14px 16px' }}>
                <div style={{ fontSize: 9, color: 'rgba(255,255,255,0.6)', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 4 }}>IBAN enregistré</div>
                <div className="af-mono" style={{ fontSize: 13, color: '#fff', fontWeight: 700, letterSpacing: 2 }}>
                  {form.iban.toUpperCase().replace(/(.{4})/g, '$1 ').trim()}
                </div>
                <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.5)', marginTop: 4 }}>{form.nom}</div>
              </div>
            )}
          </div>
        )}

        {section === 'cloud' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, animation: 'af-slide-up 0.2s both' }}>
            <div style={{ padding: '10px 12px', borderRadius: 8, background: 'rgba(11,61,92,0.08)', border: '1px solid rgba(11,61,92,0.25)', fontSize: 11, color: t.primary, lineHeight: 1.5 }}>
              Les clés d&apos;API (OpenAI, etc.) ne doivent <strong>jamais</strong> figurer dans le navigateur. Déployez un <strong>Cloudflare Worker</strong> qui détient les secrets et appelez son URL publique ci-dessous (aucun secret ici, uniquement l&apos;adresse du service).
            </div>
            <AfProfileField
              label="URL Worker unifié — tous les agents (HTTPS)"
              value={form.workersBaseUrl || ''}
              onChange={v => update('workersBaseUrl', v)}
              t={t}
              placeholder="https://instantdevis-agents.xxx.workers.dev"
              type="url"
              hint="Priorité sous `workersBase` dans `tokens.jsx` ; sinon cette URL sert d’hôte unique pour dictée, envoi, sourcing, fiscal, etc. (aucun secret). Vérification rapide : GET …/health."
            />
            <AfProfileField label="URL Worker — dictée / vocal seule (repli, HTTPS)" value={form.vocalWorkerBaseUrl || ''} onChange={v => update('vocalWorkerBaseUrl', v)} t={t}
              placeholder="https://vocal.votre-domaine.workers.dev" type="url"
              hint="Utilisé si l’URL unifiée et `workersBase` (tokens) sont vides. Le client tente POST /v1/agents/acoustic (FormData « audio »), repli 404 : /v1/vocal-ingest. Réponse JSON : { transcript, items[] } ou équivalent." />
            <div style={{ fontSize: 10, color: t.textMuted, lineHeight: 1.5 }}>
              Un seul déploiement <code>cloudflare/worker.mjs</code> peut regrouper toutes les routes ; repli e-mail : <code>AF_INTEGRATION.mailWorkerBase</code> dans <code>tokens.jsx</code> si l’URL unifiée n’est pas renseignée.
            </div>

            <div style={{ marginTop: 8, fontSize: 10, fontWeight: 800, letterSpacing: 1.2, color: t.textMuted, textTransform: 'uppercase' }}>
              Données personnelles (RGPD)
            </div>
            <div style={{ background: t.bgElevated, borderRadius: 10, border: `1px solid ${t.border}`, padding: '12px 14px', display: 'flex', flexDirection: 'column', gap: 8 }}>
              <div style={{ fontSize: 11, color: t.textMuted, lineHeight: 1.5 }}>
                Toutes vos données (profil, devis, catalogue, signatures) sont stockées localement. Vous pouvez les exporter ou les supprimer à tout moment.
              </div>
              <button
                onClick={() => {
                  const LS_KEYS = ['instantdevis_quotes_v1', 'instantdevis_profile', 'instantdevis_profile_v1', 'instantdevis_workspace_id', 'instantdevis_device_id', 'instantdevis_catalog_v1', 'instantdevis_signatures_v1', 'rgpd_consent', 'instantdevis_enable_demo'];
                  const dump = {};
                  LS_KEYS.forEach(k => { try { dump[k] = JSON.parse(localStorage.getItem(k)); } catch { dump[k] = localStorage.getItem(k); } });
                  const blob = new Blob([JSON.stringify(dump, null, 2)], { type: 'application/json' });
                  const url = URL.createObjectURL(blob);
                  const a = document.createElement('a');
                  a.href = url;
                  a.download = `instantdevis-export-${new Date().toISOString().slice(0, 10)}.json`;
                  a.click();
                  URL.revokeObjectURL(url);
                }}
                style={{ width: '100%', padding: '11px', borderRadius: 8, background: t.primary, border: 'none', fontSize: 13, fontWeight: 700, color: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7 }}
                aria-label="Exporter toutes mes données au format JSON"
              >
                <lucide.Download size={15} /> Exporter mes données (JSON)
              </button>
              <button
                onClick={() => {
                  if (!window.confirm('Supprimer TOUTES vos données locales (devis, profil, catalogue, signatures) ? Cette action est irréversible.')) return;
                  ['instantdevis_quotes_v1', 'instantdevis_profile', 'instantdevis_profile_v1', 'instantdevis_workspace_id', 'instantdevis_device_id', 'instantdevis_catalog_v1', 'instantdevis_signatures_v1', 'rgpd_consent', 'instantdevis_enable_demo'].forEach(k => localStorage.removeItem(k));
                  window.location.reload();
                }}
                style={{ width: '100%', padding: '11px', borderRadius: 8, background: 'rgba(185,28,28,0.08)', border: '1px solid rgba(185,28,28,0.3)', fontSize: 13, fontWeight: 700, color: '#B91C1C', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7 }}
                aria-label="Supprimer définitivement toutes mes données locales"
              >
                <lucide.Trash2 size={15} /> Supprimer toutes mes données
              </button>
            </div>

            <div style={{ marginTop: 8, fontSize: 10, fontWeight: 800, letterSpacing: 1.2, color: t.textMuted, textTransform: 'uppercase' }}>
              Démonstration
            </div>
            <div style={{ background: t.bgSunken, borderRadius: 10, border: `1px solid ${t.border}`, padding: '12px 14px' }}>
              {typeof afIsDemoDataEnabled === 'function' && afIsDemoDataEnabled() ? (
                <div>
                  <div style={{ fontSize: 12, color: t.text, fontWeight: 600, lineHeight: 1.5, marginBottom: 10 }}>
                    Les jeux de données de démonstration (exemples de devis et clients) sont visibles.
                  </div>
                  <button
                    type="button"
                    onClick={() => { if (typeof afSetDemoDataEnabled === 'function') afSetDemoDataEnabled(false); window.location.reload(); }}
                    style={{ width: '100%', padding: '10px 12px', borderRadius: 8, background: t.bgElevated, border: `1px solid ${t.border}`, fontSize: 13, fontWeight: 700, color: t.text, cursor: 'pointer' }}
                  >
                    Repasser en mode production (recharger)
                  </button>
                </div>
              ) : (
                <div>
                  <div style={{ fontSize: 12, color: t.textMuted, lineHeight: 1.5, marginBottom: 10 }}>
                    Par défaut, l’espace démarre sans exemples. Activez un jeu local pour prévisualiser l’app avec des devis factices.
                  </div>
                  <button
                    type="button"
                    onClick={() => { if (typeof afSetDemoDataEnabled === 'function') afSetDemoDataEnabled(true); window.location.reload(); }}
                    style={{ width: '100%', padding: '10px 12px', borderRadius: 8, background: t.primary, border: 'none', fontSize: 13, fontWeight: 700, color: '#fff', cursor: 'pointer' }}
                  >
                    Afficher les données de démonstration
                  </button>
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {/* Footer sticky */}
      <div style={{ position: 'sticky', bottom: 0, padding: '12px 16px', background: t.bg, borderTop: `1px solid ${t.border}`, display: 'flex', gap: 8 }}>
        <button onClick={onBack} type="button" style={{ width: 48, height: 52, borderRadius: 10, background: t.bgElevated, border: `1.5px solid ${t.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
          <lucide.ChevronLeft size={20} color={t.textMuted} />
        </button>
        <button type="button" id="btn-save-profile" onClick={handleSave} style={{
          flex: 1, height: 52, borderRadius: 10, border: 'none',
          background: saved ? '#10B981' : t.safety,
          fontSize: 15, fontWeight: 800, color: saved ? '#fff' : '#0D1520',
          cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          boxShadow: saved ? '0 4px 12px rgba(16,185,129,0.4)' : '0 4px 16px rgba(255,107,0,0.35)',
          transition: 'background 0.3s',
        }}>
          {saved ? <><lucide.CheckCircle2 size={18} /> Profil enregistré. Il sera réutilisé dans vos prochains devis.</> : <><lucide.Database size={18} /> Enregistrer mon profil</>}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { AfProfile, AfProfileField });
