/* global React */
/* eslint-disable */
const { useState: useStateEX, useEffect: useEffectEX, useRef: useRefEX } = React;

/* ---------- Icons ---------- */
const IconEX = {
  data: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>,
  chat: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>,
  rocket: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09Z"/><path d="m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2Z"/><path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"/><path d="M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"/></svg>,
  box: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>,
  server: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="3" width="20" height="8" rx="2"/><rect x="2" y="13" width="20" height="8" rx="2"/><line x1="6" y1="7" x2="6.01" y2="7"/><line x1="6" y1="17" x2="6.01" y2="17"/></svg>,
  external: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>,
  grid: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>,
  bell: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>,
  moon: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>,
  user: () => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>,
  logout: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>,
  sidebar: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="9" y1="3" x2="9" y2="21"/></svg>,
  link: () => <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>,
  ext: () => <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>,
  globe: () => <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>,
  search: () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>,
  eye: () => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>,
  trash: () => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-2 14a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>,
  lock: () => <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>,
};

/* ---------- Sidebar ---------- */
function ExSidebar() {
  const [progress, setProgress] = useStateEX(window.AIMakerProgress ? window.AIMakerProgress.get() : { modules:{} });
  useEffectEX(() => {
    function onP(e) { setProgress(e.detail); }
    window.addEventListener('aimaker:progress', onP);
    return () => window.removeEventListener('aimaker:progress', onP);
  }, []);
  const items = [
    { id:'data',  label: window.t('nav.data'),      icon: IconEX.data,     link:'AiMaker Dashboard.html',        mod:'data'   },
    { id:'chat',  label: window.t('nav.chat'),      icon: IconEX.chat,     link:'Fablab Chat.html',              mod:'fablab' },
    { id:'apps',  label: window.t('nav.apps'),      icon: IconEX.rocket,   link:'Gestion des applications.html', mod:'apps'   },
    { id:'prod',  label: window.t('nav.products'),  icon: IconEX.box,      link:'Produits.html',                 mod:'products' },
    { id:'srv',   label: window.t('nav.server'),    icon: IconEX.server,   link:'Serveur.html',                  mod:'server'   },
    { id:'ext',   label: window.t('nav.external'),  icon: IconEX.external, active:true,                          mod:'external' },
    { id:'work',  label: window.t('nav.workspace'), icon: IconEX.grid,   link:'Workspace.html', mod:'workspace' },
  ];
  return (
    <aside className="sidebar">
      <div className="brand">
        <div className="brand-logo">A</div>
        <div className="brand-name">AiMaker</div>
        <div className="collapse"><IconEX.sidebar/></div>
      </div>
      {items.map(it => {
        const done = it.mod && progress.modules && progress.modules[it.mod];
        const cls = 'nav-item' + (it.active?' active':'');
        const data = it.id === 'ext' ? { 'data-tour':'nav-ext' } : {};
        const content = (
          <>
            <span className="nav-icon"><it.icon/></span>
            <span style={{flex:1}}>{it.label}</span>
            {done && <span className="mod-check">✓</span>}
          </>
        );
        return it.link
          ? <a key={it.id} className={cls} href={it.link} style={{textDecoration:'none'}} {...data}>{content}</a>
          : <div key={it.id} className={cls} {...data}>{content}</div>;
      })}
      <div className="spacer"/>
      <div className="logout"><IconEX.logout/> {window.t('nav.logout')}</div>
    </aside>
  );
}

function ExTopbar() {
  return (
    <header className="topbar">
      <div className="topbar-title">{window.t('topbar.title')}</div>
      <div/>
      <div className="topbar-actions">
        <window.LangSwitcher/>
        <button className="icon-btn"><IconEX.bell/></button>
        <button className="icon-btn"><IconEX.moon/></button>
        <button className="profile-pill">
          <span className="avatar"><IconEX.user/></span>
          {window.t('topbar.profile')}
        </button>
      </div>
    </header>
  );
}

/* ---------- Initial resources ---------- */
const EXT_INITIAL = [
  { id:1, name:'Claude MCP server skills', desc:'Aimaker MCP for use with creation skills copy and paste this url in claude field...', lang:'EN', author:'admin', visibility:'public', date:'19/05/2026', tab:['all','public'] },
  { id:2, name:'Pomelli',                   desc:'',                                  lang:'FR', author:'admin', visibility:'public', date:'19/05/2026', tab:['all','public'] },
  { id:3, name:'PLAUD',                     desc:'pagina para transcripcion de video a texto', lang:'EN', author:'admin', visibility:'public', date:'14/05/2026', tab:['all','public'] },
  { id:4, name:'Reachy mini',               desc:'Robot open-source assistant para experimentación con IA', lang:'EN', author:'admin', visibility:'public', date:'12/05/2026', tab:['all','public'] },
];

/* ---------- Page ---------- */
function ExternalPage() {
  const [items, setItems] = useStateEX(EXT_INITIAL);
  const [tab, setTab]     = useStateEX('all');
  const [query, setQuery] = useStateEX('');
  const [showCreate, setShowCreate] = useStateEX(false);
  const [lastNewId, setLastNewId]   = useStateEX(null);
  const [toast, setToast]           = useStateEX(null);
  // Sim tracking
  const [created, setCreated] = useStateEX(0);
  const [madePublic, setMadePublic] = useStateEX(false);

  useEffectEX(() => {
    window.dispatchEvent(new CustomEvent('aimy:exState', { detail: { created, madePublic }}));
  }, [created, madePublic]);

  const visible = items.filter(it => {
    if (tab === 'all') return true;
    if (tab === 'mine') return it.author === 'tu';
    if (tab === 'public') return it.visibility === 'public';
    if (tab === 'private') return it.visibility === 'private';
    if (tab === 'shared') return it.shared;
    return true;
  }).filter(it => !query.trim() ? true : (it.name + ' ' + it.desc).toLowerCase().includes(query.toLowerCase()));

  function addItem(payload) {
    const id = Date.now();
    const item = {
      id,
      name: payload.name,
      desc: payload.desc,
      lang: payload.lang,
      author: 'tu',
      visibility: payload.visibility,
      date: new Date().toLocaleDateString('fr-FR'),
    };
    setItems(prev => [item, ...prev]);
    setLastNewId(id);
    setShowCreate(false);
    setCreated(c => c + 1);
    setToast({ kind:'create', name: payload.name, visibility: payload.visibility });
    setTimeout(() => setToast(null), 3000);
  }

  function toggleVisibility(it) {
    const next = it.visibility === 'public' ? 'private' : 'public';
    setItems(prev => prev.map(x => x.id === it.id ? { ...x, visibility: next } : x));
    if (it.author === 'tu' && next === 'public' && !madePublic) {
      setMadePublic(true);
    }
    setToast({ kind:'vis', name: it.name, visibility: next });
    setTimeout(() => setToast(null), 3000);
  }

  function removeItem(id) {
    setItems(prev => prev.filter(x => x.id !== id));
  }

  return (
    <main className="ext-main">
      <div className="ext-panel">
        <div className="ext-header">
          <div>
            <h1>{window.t('ext.title')}</h1>
            <p>{window.t('ext.subtitle')}</p>
          </div>
          <button className="btn-ext-create" data-tour="ext-create" onClick={()=>setShowCreate(true)}>
            <span className="plus">+</span> {window.t('btn.create')}
          </button>
        </div>

        <div className="ext-toolbar">
          <div className="ext-search" data-tour="ext-search">
            <span className="ico"><IconEX.search/></span>
            <input value={query} onChange={e=>setQuery(e.target.value)} placeholder={window.t('ext.search.placeholder')}/>
          </div>
          <div className="ext-type-select">
            <span>{window.t('ext.type.all')}</span>
            <span style={{color:'var(--text-mute)',fontSize:10}}>▾</span>
          </div>
          <div className="ext-tabs" data-tour="ext-tabs">
            {[
              {id:'all',     key:'ext.tab.all'},
              {id:'mine',    key:'ext.tab.mine'},
              {id:'shared',  key:'ext.tab.shared'},
              {id:'public',  key:'ext.tab.public'},
              {id:'private', key:'ext.tab.private'},
            ].map(tb => (
              <button key={tb.id} className={'ext-tab' + (tab===tb.id?' active':'')} onClick={()=>setTab(tb.id)}>
                {window.t(tb.key)}
              </button>
            ))}
          </div>
        </div>

        <div className="ext-table-wrap" data-tour="ext-table">
          <table className="ext-table">
            <thead>
              <tr>
                <th style={{width:140}}>{window.t('ext.col.type')}</th>
                <th>{window.t('ext.col.name')}</th>
                <th style={{width:90}}>{window.t('ext.col.lang')}</th>
                <th style={{width:140}}>{window.t('ext.col.action')}</th>
                <th style={{width:240}}>{window.t('ext.col.vis')}</th>
                <th style={{width:180}}>{window.t('ext.col.author')}</th>
              </tr>
            </thead>
            <tbody>
              {visible.length === 0 && (
                <tr><td colSpan={6}>
                  <div className="ext-empty">
                    <div className="ic">🔗</div>
                    <div style={{fontWeight:700,color:'var(--text)',marginBottom:6,fontSize:16}}>{window.t('ext.empty.title')}</div>
                    <div>{window.t('ext.empty.hint')}</div>
                  </div>
                </td></tr>
              )}
              {visible.map(it => (
                <tr key={it.id} className={it.id === lastNewId ? 'is-new' : ''}>
                  <td>
                    <div className="ext-type-cell">
                      <div className="ext-type-icon"><IconEX.link/></div>
                      <div className="ext-type-label">{window.t('ext.type.label')}</div>
                    </div>
                  </td>
                  <td>
                    <div className="ext-name">{it.name}</div>
                    {it.desc && <div className="ext-desc">{it.desc}</div>}
                  </td>
                  <td><span className="ext-lang">{it.lang}</span></td>
                  <td>
                    <div className="ext-action-cell">
                      <button className="ext-btn-voir"><IconEX.eye/> {window.t('btn.view')}</button>
                      <button className="ext-btn-del" data-tour={it.id === lastNewId ? 'ext-del' : undefined}
                              onClick={()=>removeItem(it.id)}>
                        <IconEX.trash/>
                      </button>
                    </div>
                  </td>
                  <td>
                    <div className="vis-cell">
                      <span className="vis-pill public-l"><IconEX.globe/> {it.visibility === 'public' ? 'Public' : 'Privé'}</span>
                      <span className="vis-pill public-g"
                            data-tour={it.id === lastNewId ? 'ext-visibility' : undefined}
                            onClick={()=>toggleVisibility(it)}
                            title="Cliquer pour basculer">
                        <IconEX.globe/> {it.visibility === 'public' ? 'Public' : 'Privé'} <IconEX.ext/>
                      </span>
                    </div>
                  </td>
                  <td>
                    <div className="author-cell">
                      <div className="author-avatar">{it.author === 'tu' ? 'tu' : 'ad'}</div>
                      <div className="author-meta">
                        <div className="name">{it.author}</div>
                        <div className="date">{it.date}</div>
                      </div>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {showCreate && <CreateLinkModal onCancel={()=>setShowCreate(false)} onCreate={addItem}/>}

        {toast && (
          <div className="ext-toast">
            {toast.kind === 'create' && <>✅ <strong>{toast.name}</strong> creado · visibilidad: <strong>{toast.visibility}</strong></>}
            {toast.kind === 'vis'    && <>🌐 <strong>{toast.name}</strong> ahora es <strong>{toast.visibility}</strong>{toast.visibility === 'public' ? ' · ¡compartido con la comunidad!' : ''}</>}
          </div>
        )}
      </div>
    </main>
  );
}

function CreateLinkModal({ onCancel, onCreate }) {
  const [form, setForm] = useStateEX({ name:'', url:'', desc:'', lang:'ES', visibility:'private' });
  const valid = form.name.trim() && form.url.trim();
  return (
    <div className="modal-back" onClick={onCancel}>
      <div className="modal ext-modal" onClick={e=>e.stopPropagation()} data-tour="ext-modal">
        <h3>{window.t('ext.modal.title')}</h3>
        <p className="sub">{window.t('ext.modal.sub')}</p>
        <div className="form-row">
          <label>{window.t('ext.form.name')}</label>
          <input value={form.name} onChange={e=>setForm(f=>({...f, name:e.target.value}))} className="input"/>
        </div>
        <div className="form-row">
          <label>{window.t('ext.form.url')}</label>
          <input value={form.url} onChange={e=>setForm(f=>({...f, url:e.target.value}))} className="input" placeholder="https://..."/>
        </div>
        <div className="form-row">
          <label>{window.t('ext.form.desc')}</label>
          <textarea rows={2} value={form.desc} onChange={e=>setForm(f=>({...f, desc:e.target.value}))} className="input"/>
        </div>
        <div className="form-row">
          <label>{window.t('ext.form.lang')}</label>
          <div className="lang-picker">
            {['ES','EN','FR'].map(l => (
              <button key={l} className={'lang-btn' + (form.lang===l?' active':'')} onClick={()=>setForm(f=>({...f, lang:l}))}>{l}</button>
            ))}
          </div>
        </div>
        <div className="form-row">
          <label>{window.t('ext.form.vis')}</label>
          <div className="vis-picker">
            <button className={'vis-card' + (form.visibility==='private'?' active':'')} onClick={()=>setForm(f=>({...f, visibility:'private'}))}>
              <div className="vt">{window.t('ext.vis.priv.title')}</div>
              <div className="vd">{window.t('ext.vis.priv.desc')}</div>
            </button>
            <button className={'vis-card' + (form.visibility==='public'?' active':'')} onClick={()=>setForm(f=>({...f, visibility:'public'}))}>
              <div className="vt">{window.t('ext.vis.pub.title')}</div>
              <div className="vd">{window.t('ext.vis.pub.desc')}</div>
            </button>
          </div>
        </div>
        <div className="modal-actions">
          <button className="btn-cancel" onClick={onCancel}>{window.t('btn.cancel')}</button>
          <button className="btn-create" disabled={!valid} onClick={()=>onCreate(form)}>{window.t('btn.create')}</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { IconEX, ExSidebar, ExTopbar, ExternalPage });
