// ============================================================
// WASIED · Admin CMS - full live editor (writes to CMS store)
// ============================================================

const THUMB_OPTIONS = ['gradient-cyan', 'gradient-green', 'gradient-indigo', 'gradient-amber', 'gradient-purple', 'gradient-red'];
const THUMB_CSS = {
  'gradient-cyan': 'linear-gradient(135deg, #0E7490, #67E8F9)',
  'gradient-green': 'linear-gradient(135deg, #15803D, #6EE7A7)',
  'gradient-indigo': 'linear-gradient(135deg, #4F5DBE, #8FA8FF)',
  'gradient-amber': 'linear-gradient(135deg, #B45309, #FBBF24)',
  'gradient-purple': 'linear-gradient(135deg, #7E22CE, #C4B5FD)',
  'gradient-red': 'linear-gradient(135deg, #B91C1C, #FB7185)',
};

function AdminContentPage() {
  const cms = useCMS();
  const [tab, setTab] = React.useState('hero');
  const [saved, setSaved] = React.useState(false);

  const flash = () => { setSaved(true); setTimeout(() => setSaved(false), 1600); };

  const tabs = [
    { k: 'hero', label: 'Hero homepage', icon: 'dashboard' },
    { k: 'clients', label: 'Clients (marquee)', icon: 'users' },
    { k: 'media', label: 'Vidéos & images', icon: 'video' },
    { k: 'showcase', label: 'Aperçu produit', icon: 'layers' },
    { k: 'seo', label: 'SEO & méta', icon: 'globe' },
    { k: 'site', label: 'Réglages du site', icon: 'settings' },
  ];

  return (
    <AppShell isAdmin title="Contenu · CMS" breadcrumbs={[{ label: 'Admin', path: '/admin' }, { label: 'Contenu' }]}
      actions={
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {saved && <span style={{ fontSize: 12, color: 'var(--cash)', display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="check" size={13}/>Enregistré & publié</span>}
          <Button variant="ghost" size="sm" href="#/" >Voir le site</Button>
          <Button variant="ghost" size="sm" icon="refresh" onClick={() => { if (confirm('Réinitialiser tout le contenu aux valeurs par défaut ?')) { resetCMS(); flash(); } }}>Réinitialiser</Button>
        </div>
      }>
      <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr', gap: 18 }} className="dash-main">
        {/* Section nav */}
        <div style={{ position: 'sticky', top: 80, alignSelf: 'flex-start' }}>
          <Panel style={{ padding: 8 }}>
            {tabs.map(t => (
              <button key={t.k} onClick={() => setTab(t.k)} style={{
                display: 'flex', width: '100%', alignItems: 'center', gap: 10, padding: '9px 10px',
                borderRadius: 7, border: 'none', cursor: 'pointer', textAlign: 'left',
                background: tab === t.k ? 'var(--accent-soft)' : 'transparent',
                color: tab === t.k ? 'var(--fg-1)' : 'var(--fg-2)', fontSize: 13, fontWeight: 500, marginBottom: 2,
              }}>
                <Icon name={t.icon} size={15} color={tab === t.k ? 'var(--accent)' : 'currentColor'}/>{t.label}
              </button>
            ))}
          </Panel>
          <div style={{ marginTop: 12, padding: 14, background: 'rgba(110,231,167,0.05)', border: '1px solid rgba(110,231,167,0.16)', borderRadius: 10, fontSize: 11, color: 'var(--fg-3)', lineHeight: 1.5 }}>
            <Icon name="info" size={13} color="var(--cash)" style={{ marginBottom: 6 }}/>
            <div>Les modifications sont <strong style={{ color: 'var(--fg-2)' }}>publiées en direct</strong> sur le site public. Ouvrez l'accueil dans un autre onglet pour voir le résultat.</div>
          </div>
        </div>

        {/* Editor */}
        <div>
          {tab === 'hero' && <CmsHero cms={cms} flash={flash}/>}
          {tab === 'clients' && <CmsClients cms={cms} flash={flash}/>}
          {tab === 'media' && <CmsMedia cms={cms} flash={flash}/>}
          {tab === 'showcase' && <CmsShowcase cms={cms} flash={flash}/>}
          {tab === 'seo' && <CmsSeo cms={cms} flash={flash}/>}
          {tab === 'site' && <CmsSite cms={cms} flash={flash}/>}
        </div>
      </div>
    </AppShell>
  );
}

// ---------- Hero editor ----------
function CmsHero({ cms, flash }) {
  const h = cms.hero;
  const set = (k, v) => setCMS(s => { s.hero[k] = v; return s; });
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <CmsPanel title="Bandeau d'accroche (eyebrow)">
        <CmsField label="Texte de l'eyebrow" value={h.eyebrow} onChange={v => set('eyebrow', v)}/>
      </CmsPanel>
      <CmsPanel title="Titre principal">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <CmsField label="Ligne 1" value={h.titleLine1} onChange={v => set('titleLine1', v)}/>
          <CmsField label="Ligne 2" value={h.titleLine2} onChange={v => set('titleLine2', v)}/>
        </div>
        <CmsField label="Mot accentué (en indigo)" value={h.titleAccent} onChange={v => set('titleAccent', v)}/>
      </CmsPanel>
      <CmsPanel title="Sous-titre">
        <CmsField textarea label="Texte" value={h.lede} onChange={v => set('lede', v)}/>
      </CmsPanel>
      <CmsPanel title="Boutons d'action">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <CmsField label="CTA primaire · libellé" value={h.ctaPrimaryLabel} onChange={v => set('ctaPrimaryLabel', v)}/>
          <CmsField label="CTA primaire · lien" value={h.ctaPrimaryHref} onChange={v => set('ctaPrimaryHref', v)}/>
          <CmsField label="CTA secondaire · libellé" value={h.ctaSecondaryLabel} onChange={v => set('ctaSecondaryLabel', v)}/>
          <CmsField label="CTA secondaire · lien" value={h.ctaSecondaryHref} onChange={v => set('ctaSecondaryHref', v)}/>
        </div>
        <CmsField label="Ligne d'infos sous les boutons" value={h.metaLine} onChange={v => set('metaLine', v)}/>
      </CmsPanel>
      <CmsLivePreview>
        <div style={{ padding: 24 }}>
          <div style={{ fontSize: 11, color: 'var(--fg-2)', marginBottom: 12 }}>{h.eyebrow}</div>
          <div className="h-display" style={{ fontSize: 28, letterSpacing: '-0.03em', lineHeight: 1.1, marginBottom: 10 }}>
            {h.titleLine1} {h.titleLine2} <span style={{ color: 'var(--accent)' }}>{h.titleAccent}</span>
          </div>
          <div style={{ fontSize: 13, color: 'var(--fg-2)', maxWidth: 460, marginBottom: 14 }}>{h.lede}</div>
          <div style={{ display: 'flex', gap: 8 }}>
            <span style={{ padding: '7px 12px', background: 'var(--fg-1)', color: 'var(--fg-inv)', borderRadius: 8, fontSize: 12, fontWeight: 500 }}>{h.ctaPrimaryLabel}</span>
            <span style={{ padding: '7px 12px', border: '1px solid var(--border-2)', borderRadius: 8, fontSize: 12, fontWeight: 500, color: 'var(--fg-2)' }}>{h.ctaSecondaryLabel}</span>
          </div>
        </div>
      </CmsLivePreview>
      <SaveBar onSave={flash}/>
    </div>
  );
}

// ---------- Clients editor ----------
function CmsClients({ cms, flash }) {
  const [draft, setDraft] = React.useState('');
  const clients = cms.clients;
  const addClient = () => {
    const names = draft.split(',').map(s => s.trim()).filter(Boolean);
    if (!names.length) return;
    setCMS(s => { s.clients = [...s.clients, ...names]; return s; });
    setDraft('');
  };
  const remove = (i) => setCMS(s => { s.clients = s.clients.filter((_, j) => j !== i); return s; });
  const move = (i, dir) => setCMS(s => {
    const arr = [...s.clients]; const j = i + dir;
    if (j < 0 || j >= arr.length) return s;
    [arr[i], arr[j]] = [arr[j], arr[i]]; s.clients = arr; return s;
  });
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <CmsPanel title="Légende du bandeau clients">
        <CmsField label="Texte affiché au-dessus du défilé" value={cms.clientsCaption} onChange={v => setCMS(s => { s.clientsCaption = v; return s; })}/>
      </CmsPanel>
      <CmsPanel title={`Liste des clients (${clients.length})`}>
        <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
          <Input placeholder="Ajouter un ou plusieurs noms, séparés par des virgules…" value={draft} onChange={e => setDraft(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') addClient(); }}/>
          <Button variant="primary" size="md" icon="plus" onClick={addClient}>Ajouter</Button>
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {clients.map((c, i) => (
            <div key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 8px 6px 12px', background: 'var(--surface-2)', border: '1px solid var(--border-1)', borderRadius: 999 }}>
              <span style={{ fontSize: 13, color: 'var(--fg-1)', fontWeight: 500 }}>{c}</span>
              <div style={{ display: 'flex', gap: 2 }}>
                <button onClick={() => move(i, -1)} style={cmsIconBtn} title="Reculer"><Icon name="chevronLeft" size={12}/></button>
                <button onClick={() => move(i, 1)} style={cmsIconBtn} title="Avancer"><Icon name="chevron" size={12}/></button>
                <button onClick={() => remove(i)} style={{ ...cmsIconBtn, color: 'var(--hp)' }} title="Supprimer"><Icon name="x" size={12}/></button>
              </div>
            </div>
          ))}
        </div>
      </CmsPanel>
      <CmsLivePreview>
        <div style={{ padding: '20px 0', overflow: 'hidden' }}>
          <div style={{ padding: '0 20px', fontSize: 10, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 12 }}>{cms.clientsCaption}</div>
          <div style={{ display: 'flex', gap: 24, padding: '0 20px', flexWrap: 'wrap' }}>
            {clients.slice(0, 14).map((c, i) => <span key={i} style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 16, color: 'var(--fg-3)', opacity: 0.7 }}>{c}</span>)}
            {clients.length > 14 && <span style={{ fontSize: 13, color: 'var(--fg-4)' }}>+{clients.length - 14}</span>}
          </div>
        </div>
      </CmsLivePreview>
      <SaveBar onSave={flash}/>
    </div>
  );
}

// ---------- Media editor ----------
function CmsMedia({ cms, flash }) {
  const media = cms.media || [];
  const addMedia = (type) => setCMS(s => {
    const id = 'm' + (Date.now());
    s.media = [...(s.media || []), { id, type, title: type === 'video' ? 'Nouvelle vidéo' : 'Nouvelle image', client: '', tag: 'UI', duration: type === 'video' ? '0:00' : null, thumb: THUMB_OPTIONS[(s.media || []).length % THUMB_OPTIONS.length], published: false }];
    return s;
  });
  const update = (id, k, v) => setCMS(s => { s.media = s.media.map(m => m.id === id ? { ...m, [k]: v } : m); return s; });
  const remove = (id) => setCMS(s => { s.media = s.media.filter(m => m.id !== id); return s; });

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <CmsPanel title="Médias de présentation"
        action={
          <div style={{ display: 'flex', gap: 8 }}>
            <Button variant="ghost" size="sm" icon="video" onClick={() => addMedia('video')}>Ajouter vidéo</Button>
            <Button variant="ghost" size="sm" icon="image" onClick={() => addMedia('image')}>Ajouter image</Button>
          </div>
        }>
        <p style={{ fontSize: 12, color: 'var(--fg-3)', margin: '0 0 16px' }}>
          Les médias publiés apparaissent dans la section « Démos » de la page Portfolio. Glissez vos fichiers ou collez une URL ; ici on simule avec une vignette colorée.
        </p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {media.map(m => (
            <div key={m.id} style={{ display: 'grid', gridTemplateColumns: '140px 1fr auto', gap: 16, padding: 14, background: 'var(--surface-2)', border: '1px solid var(--border-1)', borderRadius: 10, alignItems: 'flex-start' }}>
              {/* Thumb + drop zone */}
              <div>
                <div style={{ aspectRatio: '16/9', borderRadius: 8, background: THUMB_CSS[m.thumb], position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
                  {m.type === 'video'
                    ? <div style={{ width: 32, height: 32, borderRadius: '50%', background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="play" size={14} color="#fff" style={{ fill: '#fff', marginLeft: 2 }}/></div>
                    : <Icon name="image" size={20} color="rgba(255,255,255,0.85)"/>}
                </div>
                <div style={{ display: 'flex', gap: 3, marginTop: 6, flexWrap: 'wrap' }}>
                  {THUMB_OPTIONS.map(t => (
                    <button key={t} onClick={() => update(m.id, 'thumb', t)} title={t} style={{ width: 16, height: 16, borderRadius: 4, background: THUMB_CSS[t], border: m.thumb === t ? '2px solid var(--fg-1)' : '1px solid var(--border-2)', cursor: 'pointer', padding: 0 }}/>
                  ))}
                </div>
              </div>
              {/* Fields */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                <Input value={m.title} onChange={e => update(m.id, 'title', e.target.value)} containerStyle={{ marginBottom: 0 }}/>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
                  <Input placeholder="Client" value={m.client} onChange={e => update(m.id, 'client', e.target.value)}/>
                  <Input placeholder="Tag" value={m.tag} onChange={e => update(m.id, 'tag', e.target.value)}/>
                  {m.type === 'video'
                    ? <Input placeholder="Durée" value={m.duration || ''} onChange={e => update(m.id, 'duration', e.target.value)}/>
                    : <span style={{ display: 'flex', alignItems: 'center', fontSize: 11, color: 'var(--fg-3)' }}>Image</span>}
                </div>
                <button style={{ alignSelf: 'flex-start', display: 'inline-flex', alignItems: 'center', gap: 6, padding: '6px 10px', border: '1px dashed var(--border-2)', borderRadius: 7, background: 'transparent', color: 'var(--fg-3)', fontSize: 11, cursor: 'pointer' }}>
                  <Icon name="upload" size={12}/>{m.type === 'video' ? 'Téléverser un MP4 / coller une URL' : 'Téléverser une image'}
                </button>
              </div>
              {/* Actions */}
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8 }}>
                <Toggle on={m.published} onChange={v => update(m.id, 'published', v)} label="Publié"/>
                <button onClick={() => remove(m.id)} style={{ ...cmsIconBtn, color: 'var(--hp)' }}><Icon name="trash" size={14}/></button>
              </div>
            </div>
          ))}
          {!media.length && <div style={{ padding: 32, textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>Aucun média. Ajoutez une vidéo ou une image.</div>}
        </div>
      </CmsPanel>
      <SaveBar onSave={flash}/>
    </div>
  );
}

// ---------- Showcase toggles ----------
function CmsShowcase({ cms, flash }) {
  const sh = cms.showcaseEnabled;
  const set = (k, v) => setCMS(s => { s.showcaseEnabled[k] = v; return s; });
  const items = [
    { k: 'hosting', label: 'Hébergement · console live' },
    { k: 'orders', label: 'Commandes · suivi' },
    { k: 'formations', label: 'Formations · player' },
    { k: 'billing', label: 'Facturation · cartes' },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <CmsPanel title="Onglets de l'aperçu produit (homepage)">
        <p style={{ fontSize: 12, color: 'var(--fg-3)', margin: '0 0 12px' }}>Activez ou masquez chaque onglet de la section « Un seul dashboard ».</p>
        {items.map(it => <Toggle key={it.k} on={sh[it.k]} onChange={v => set(it.k, v)} label={it.label}/>)}
      </CmsPanel>
      <SaveBar onSave={flash}/>
    </div>
  );
}

// ---------- SEO ----------
function CmsSeo({ cms, flash }) {
  const s0 = cms.seo;
  const set = (k, v) => setCMS(s => { s.seo[k] = v; return s; });
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <CmsPanel title="Métadonnées globales">
        <CmsField label="Titre (balise title)" value={s0.title} onChange={v => set('title', v)}/>
        <CmsField textarea label="Meta description" value={s0.description} onChange={v => set('description', v)}/>
      </CmsPanel>
      <CmsPanel title="Aperçu moteur de recherche">
        <div style={{ padding: 16, background: 'var(--surface-2)', borderRadius: 8 }}>
          <div style={{ fontSize: 12, color: 'var(--service-hosting)' }}>wasied.com</div>
          <div style={{ fontSize: 17, color: 'var(--accent)', margin: '2px 0', letterSpacing: '-0.01em' }}>{s0.title}</div>
          <div style={{ fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.4 }}>{s0.description}</div>
        </div>
      </CmsPanel>
      <SaveBar onSave={flash}/>
    </div>
  );
}

// ---------- Site settings ----------
function CmsSite({ cms, flash }) {
  const st = cms.site;
  const set = (k, v) => setCMS(s => { s.site[k] = v; return s; });
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <CmsPanel title="Statut « Disponibilité » (Hire me)">
        <div style={{ display: 'flex', gap: 8 }}>
          {[
            { v: 'available', label: 'Disponible', c: 'var(--cash)' },
            { v: 'limited', label: 'Capacité limitée', c: 'var(--xp)' },
            { v: 'busy', label: 'Complet', c: 'var(--hp)' },
          ].map(o => (
            <button key={o.v} onClick={() => { set('hireStatus', o.v); window.__hireStatus = o.v; }} style={{
              display: 'inline-flex', alignItems: 'center', gap: 8,
              padding: '12px 18px', background: st.hireStatus === o.v ? 'var(--surface-3)' : 'var(--surface-2)',
              border: `1px solid ${st.hireStatus === o.v ? 'var(--border-3)' : 'var(--border-1)'}`,
              borderRadius: 8, cursor: 'pointer', fontSize: 13, fontWeight: 500, color: 'var(--fg-1)',
            }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: o.c }}/>{o.label}
            </button>
          ))}
        </div>
      </CmsPanel>
      <CmsPanel title="Bandeau d'annonce">
        <CmsField label="Texte (laisser vide pour masquer)" value={st.announcement} onChange={v => set('announcement', v)} placeholder="Ex : Maintenance prévue dimanche 2h-4h"/>
      </CmsPanel>
      <CmsPanel title="Mode maintenance">
        <Toggle on={st.maintenanceMode} onChange={v => set('maintenanceMode', v)} label="Activer le mode maintenance" sub="Affiche une page de maintenance aux visiteurs (admins exclus)."/>
      </CmsPanel>
      <SaveBar onSave={flash}/>
    </div>
  );
}

// ---------- Shared CMS UI ----------
const cmsIconBtn = { width: 22, height: 22, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', background: 'transparent', border: 'none', borderRadius: 5, cursor: 'pointer', color: 'var(--fg-3)', padding: 0 };

function CmsPanel({ title, action, children }) {
  return (
    <Panel style={{ padding: 22 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
        <h3 style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg-1)', margin: 0 }}>{title}</h3>
        {action}
      </div>
      {children}
    </Panel>
  );
}

function CmsField({ label, value, onChange, textarea, placeholder }) {
  return (
    <div style={{ marginBottom: 12 }}>
      {textarea
        ? <Textarea label={label} value={value} placeholder={placeholder} onChange={e => onChange(e.target.value)} style={{ minHeight: 80 }}/>
        : <Input label={label} value={value} placeholder={placeholder} onChange={e => onChange(e.target.value)}/>}
    </div>
  );
}

function CmsLivePreview({ children }) {
  return (
    <div>
      <div style={{ fontSize: 11, color: 'var(--fg-3)', fontWeight: 500, marginBottom: 8, display: 'flex', alignItems: 'center', gap: 6 }}>
        <Icon name="eye" size={13}/>APERÇU EN DIRECT
      </div>
      <div style={{ background: 'var(--surface-0)', border: '1px solid var(--border-2)', borderRadius: 10, overflow: 'hidden' }}>
        {children}
      </div>
    </div>
  );
}

function SaveBar({ onSave }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 0' }}>
      <span style={{ fontSize: 12, color: 'var(--fg-3)', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
        <Icon name="check" size={13} color="var(--cash)"/>Sauvegarde automatique · publié en direct
      </span>
      <Button variant="primary" size="sm" icon="check" onClick={onSave} style={{ marginLeft: 'auto' }}>Confirmer la publication</Button>
    </div>
  );
}

Object.assign(window, { AdminContentPage });
