// MainView.jsx — 单行顶栏（Logo + 工具行）+ 多引擎墨吞 + 真实导入
const { useState: useStateMV, useRef: useRefMV, useEffect: useEffectMV } = React;

// —— 点击外部关闭 —— //
function useOutside(ref, onClose) {
  useEffectMV(() => {
    function h(e) { if (ref.current && !ref.current.contains(e.target)) onClose(); }
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [onClose]);
}

// ============ 下拉菜单包装 ============
function ToolMenu({ icon, label, children, align }) {
  const [open, setOpen] = useStateMV(false);
  const ref = useRefMV(null);
  useOutside(ref, () => setOpen(false));
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button className={'tool-btn' + (open ? ' on' : '')} onClick={() => setOpen(o => !o)}>
        <Icon name={icon} size={15} />
        <span>{label}</span>
        <Icon name="chevDown" size={11} className="chev" />
      </button>
      {open && (
        <div className={'dropdown' + (align === 'right' ? ' right' : '')} onClick={() => setOpen(false)}>
          {children}
        </div>
      )}
    </div>
  );
}
function DDItem({ icon, children, k, onClick }) {
  return (
    <div className="dd-item" onClick={onClick}>
      {icon && <Icon name={icon} size={16} />}
      <span>{children}</span>
      {k && <span className="k">{k}</span>}
    </div>
  );
}

// ============ 墨吞 · 接入 AI 引擎（多引擎 · 可扩展）============
function MotunSettings() {
  const [open, setOpen] = useStateMV(false);
  const ref = useRefMV(null);
  useOutside(ref, () => setOpen(false));

  const [providers, setProviders] = useStateMV(() => getProviders());
  const [active, setActive] = useStateMV(() => getActiveId());
  const cur = providers.find(p => p.id === active) || providers[0];

  const [apiKey, setApiKey] = useStateMV(() => getKey(active));
  const [model, setModelS] = useStateMV(() => getModel(active));
  const [base, setBaseS] = useStateMV(() => getBase(active));
  const [proxy, setProxyS] = useStateMV(() => getProxy());
  const [show, setShow] = useStateMV(false);
  const [status, setStatus] = useStateMV('idle'); // idle|saved|testing|ok|err
  const [msg, setMsg] = useStateMV('');
  const [adding, setAdding] = useStateMV(false);
  const [nf, setNf] = useStateMV({ name: '', base: '', model: '' });

  function pickProvider(id) {
    setActiveId(id); setActive(id);
    setApiKey(getKey(id)); setModelS(getModel(id)); setBaseS(getBase(id));
    setStatus('idle'); setMsg('');
  }
  function persist() {
    setKey(active, apiKey.trim());
    setBase(active, base.trim() === cur.base ? '' : base.trim());
    setModel(active, model);
    setProxy(proxy.trim());
    setProviders(getProviders());
  }
  function save() { persist(); setStatus('saved'); setMsg('已保存在本机'); }
  async function test() {
    persist(); setStatus('testing'); setMsg('正在连接 ' + cur.name + '…');
    try { const r = await aiPing(); setStatus('ok'); setMsg('连接成功 · 「' + r + '」'); }
    catch (e) { setStatus('err'); setMsg(e.message || '连接失败'); }
  }
  function createCustom() {
    if (!nf.name.trim() || !nf.base.trim()) return;
    const id = addCustomProvider({ name: nf.name.trim(), base: nf.base.trim(), models: nf.model.trim() ? [nf.model.trim()] : ['default'] });
    setProviders(getProviders()); setAdding(false); setNf({ name: '', base: '', model: '' });
    pickProvider(id);
  }
  function deleteCustom(id, e) {
    e.stopPropagation();
    removeCustomProvider(id);
    const left = getProviders(); setProviders(left);
    if (active === id) pickProvider('deepseek');
  }

  const connected = hasActiveKey();
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button className={'tool-btn motun-btn' + (open ? ' on' : '')} onClick={() => setOpen(o => !o)}>
        <span className={'motun-dot' + (connected ? ' on' : '')}></span>
        <Icon name="spark" size={15} />
        <span>墨吞</span>
        <Icon name="chevDown" size={11} className="chev" />
      </button>
      {open && (
        <div className="dropdown right ai-dd" onClick={e => e.stopPropagation()}>
          <div className="ai-dd-head">
            <span className="motun-ava">墨</span>
            <div>
              <div className="ai-dd-t">墨吞 · 接入 AI 引擎</div>
              <div className="ai-dd-s">选一个引擎、填入你自己的密钥。可同时保存多家、随时切换。密钥仅存本机。</div>
            </div>
          </div>

          <div className="ai-dd-label">引擎</div>
          <div className="ai-provs">
            {providers.map(p => (
              <button key={p.id} className={'ai-prov' + (active === p.id ? ' on' : '')} onClick={() => pickProvider(p.id)}>
                <span className="ai-av">{p.av}</span>
                <span className="ai-pmeta">
                  <span className="ai-pname">{p.name}{getKey(p.id) || p.id === 'local' ? <span className="ai-have">已接入</span> : null}</span>
                  <span className="ai-psub">{p.sub}</span>
                </span>
                {p.custom && <span className="ai-del" onClick={e => deleteCustom(p.id, e)} title="移除"><Icon name="x" size={11} /></span>}
                <span className="ai-radio">{active === p.id && <Icon name="check" size={12} />}</span>
              </button>
            ))}
            {adding ? (
              <div className="ai-newprov">
                <input placeholder="名称（如：MiniMax）" value={nf.name} onChange={e => setNf({ ...nf, name: e.target.value })} />
                <input placeholder="接口地址（OpenAI 兼容）" value={nf.base} onChange={e => setNf({ ...nf, base: e.target.value })} />
                <input placeholder="模型名（可选）" value={nf.model} onChange={e => setNf({ ...nf, model: e.target.value })} />
                <div className="ai-newprov-acts">
                  <button onClick={() => setAdding(false)}>取消</button>
                  <button className="primary" onClick={createCustom}>添加</button>
                </div>
              </div>
            ) : (
              <button className="ai-addprov" onClick={() => setAdding(true)}><Icon name="plus" size={13} /> 扩展 · 接入其它引擎</button>
            )}
          </div>

          <div className="ai-dd-label">{cur.name} · API Key</div>
          <div className="ds-keyrow">
            <input className="ai-key" type={show ? 'text' : 'password'} value={apiKey} spellCheck={false}
              placeholder={cur.keyHint} onChange={e => { setApiKey(e.target.value); setStatus('idle'); }} />
            <button className="ds-eye" title={show ? '隐藏' : '显示'} onClick={() => setShow(s => !s)}>
              <Icon name={show ? 'eye' : 'search'} size={13} />
            </button>
          </div>

          <details className="ds-adv">
            <summary><Icon name="chevRight" size={11} /> 进阶 · 接口地址与模型</summary>
            <div className="ai-dd-label">接口地址</div>
            <input className="ai-key" type="text" value={base} spellCheck={false}
              placeholder={cur.base} onChange={e => setBaseS(e.target.value)} />
            <div className="ai-dd-label">模型</div>
            <div className="ds-models">
              {cur.models.map(m => (
                <button key={m} className={'ds-model' + (model === m ? ' on' : '')} onClick={() => setModelS(m)}>{m}</button>
              ))}
            </div>
            <div className="ai-dd-label">代理地址 · 可选</div>
            <input className="ai-key" type="text" value={proxy} spellCheck={false}
              placeholder="https://你的代理.workers.dev" onChange={e => setProxyS(e.target.value)} />
            <div className="ai-custom-hint">浏览器直连 Claude / Gemini 常被跨域拦截。部署一个代理后填这里，全部引擎即可直连。</div>
          </details>

          {msg && <div className={'ds-status ' + status}>
            {status === 'ok' && <Icon name="check" size={12} />}
            {status === 'err' && <Icon name="x" size={12} />}
            {status === 'testing' && <Icon name="refresh" size={12} className="spin" />}
            {msg}
          </div>}

          <div className="ds-actions">
            <button className="ds-save" onClick={save}><Icon name="save" size={13} /> 保存</button>
            <button className="ds-test" onClick={test} disabled={(!apiKey.trim() && cur.id !== 'local') || status === 'testing'}>
              <Icon name="zap" size={13} /> 测试连接
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// ============ 顶栏（单行：Logo + 工具行）============
function TopBar({ notebooks, onImport, onOpenContacts, onOpenSkills, onOpenShare, onOpenInbox, inboxCount, onOpenPlans }) {
  const fileRef = useRefMV(null);
  function pick(kind) {
    const inp = fileRef.current; if (!inp) return;
    inp.accept = (kind === 'image' || kind === 'camera') ? 'image/*'
      : kind === 'word' ? '.doc,.docx'
      : kind === 'pdf' ? '.pdf,application/pdf'
      : '.txt,.md,.markdown,text/plain';
    if (kind === 'camera') inp.setAttribute('capture', 'environment'); else inp.removeAttribute('capture');
    inp.click();
  }
  function onFile(e) {
    const f = e.target.files && e.target.files[0];
    e.target.value = '';
    if (f) onImport(f);
  }
  return (
    <div className="topbar">
      <div className="brandmark"><PoporMark height={22} /></div>
      <span className="top-div"></span>

      <div className="tool-grp">
        <ToolMenu icon="layers" label="分类">
          <div className="dd-label">按本子</div>
          {notebooks.map(nb => <DDItem key={nb.id} icon={nb.lineIcon}>{nb.name}</DDItem>)}
          <div className="dd-div"></div>
          <DDItem icon="filter">自定义筛选</DDItem>
        </ToolMenu>

        <ToolMenu icon="download" label="导入">
          <div className="dd-label">从文件导入到书写台</div>
          <DDItem icon="type" k="TXT · MD" onClick={() => pick('text')}>纯文本 / Markdown</DDItem>
          <DDItem icon="book" k="DOC · DOCX" onClick={() => pick('word')}>Word 文档</DDItem>
          <DDItem icon="book" k="PDF" onClick={() => pick('pdf')}>PDF 文档</DDItem>
          <div className="dd-div"></div>
          <DDItem icon="image" k="相册" onClick={() => pick('image')}>照片导入</DDItem>
          <DDItem icon="camera" k="OCR" onClick={() => pick('camera')}>拍照 · 识别</DDItem>
        </ToolMenu>

        <button className="tool-btn" title="技能工具箱" onClick={onOpenSkills}>
          <Icon name="grid" size={15} /><span>工具箱</span>
        </button>
        {typeof InboxButton === 'function' && <InboxButton count={inboxCount} onClick={onOpenInbox} />}
        <button className="tool-btn" title="通讯录" onClick={onOpenContacts}>
          <Icon name="users" size={15} /><span>通讯录</span>
        </button>
        <button className="tool-btn icon-only" title="分享" onClick={onOpenShare}><Icon name="share" size={15} /></button>
        <button className="tool-btn icon-only" title="通知"><Icon name="bell" size={15} /></button>
        <MotunSettings />
      </div>

      <div className="func-spacer"></div>

      <div className="top-right">
        <button className="lb-icon" title="搜索"><Icon name="search" size={16} /></button>
        <button className="lb-icon" title="外观"><Icon name="sun" size={16} /></button>
      </div>

      <input ref={fileRef} type="file" hidden onChange={onFile} />
    </div>
  );
}

Object.assign(window, { TopBar, MotunSettings, useOutside });
