/* 業務OS — App shell with tab nav + sidebar integrations + task detail */

function AppShell() {
  const D = window.GYOMU;
  const [view, setView] = useState('todo');
  const [detailTaskId, setDetailTaskId] = useState(null);
  const [activeIntegration, setActiveIntegration] = useState(null);

  const tabs = [
    { key: 'todo', label: 'TODO', icon: 'check-square' },
    { key: 'queue', label: '業務キュー', icon: 'list' },
    { key: 'skills', label: 'スキル', icon: 'zap' },
    { key: 'knowledge', label: 'ナレッジ', icon: 'book-open' },
  ];

  const integrationViews = [
    { key: 'outlook', icon: 'mail', label: 'Outlook', color: 'var(--info)' },
    { key: 'teams', icon: 'message-square', label: 'Teams', color: 'var(--stage-s0)' },
    { key: 'salesforce', icon: 'database', label: 'Salesforce', color: 'var(--success)' },
  ];

  /* Tab pill animation */
  const navRef = useRef(null);
  const [pill, setPill] = useState({ left: 3, width: 0 });
  useEffect(() => {
    const nav = navRef.current;
    if (!nav) return;
    const active = nav.querySelector('[data-active="true"]');
    if (active) setPill({ left: active.offsetLeft, width: active.offsetWidth });
  }, [view]);

  const handleTabClick = (key) => {
    setView(key);
    setDetailTaskId(null);
    setActiveIntegration(null);
  };

  const handleIntegrationClick = (key) => {
    if (activeIntegration === key) {
      setActiveIntegration(null);
    } else {
      setActiveIntegration(key);
      setDetailTaskId(null);
    }
  };

  const handleOpenDetail = (taskId) => {
    setDetailTaskId(taskId);
    setActiveIntegration(null);
  };

  const handleBackFromDetail = () => {
    setDetailTaskId(null);
  };

  /* Determine what's shown in center */
  const showingIntegration = activeIntegration !== null;
  const showingDetail = detailTaskId !== null && !showingIntegration;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100vh', background: 'var(--bg)', fontFamily: 'var(--font-sans)', color: 'var(--text-1)' }}>
      {/* HEADER */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, minHeight: 52, padding: '10px 20px', borderBottom: '1px solid var(--border)', background: 'var(--surface)', flexShrink: 0, zIndex: 50 }}>
        <div style={{ display: 'flex', gap: 7, flexShrink: 0 }}>
          {['#ff5f57', '#febc2e', '#28c840'].map((c, i) => <div key={i} style={{ width: 12, height: 12, borderRadius: '50%', background: c, border: '0.5px solid rgba(0,0,0,.1)' }} />)}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
          <img src="assets/gauge-mark.svg" alt="" style={{ width: 20, height: 20 }} />
          <span style={{ fontSize: 12, fontWeight: 600, letterSpacing: '.06em', color: 'var(--text-2)', textTransform: 'uppercase' }}>
            <span style={{ color: 'var(--accent)' }}>業務</span>OS
          </span>
        </div>

        {/* Tab nav */}
        <nav ref={navRef} style={{ display: 'flex', background: 'var(--bg)', borderRadius: 6, padding: 3, position: 'relative', flexShrink: 0, marginLeft: 8 }}>
          {tabs.map(t => (
            <button key={t.key} data-active={view === t.key && !showingIntegration ? 'true' : 'false'}
              onClick={() => handleTabClick(t.key)}
              style={{
                fontFamily: 'inherit', fontSize: 11, fontWeight: 500, letterSpacing: '.03em',
                padding: '5px 14px', background: 'none', border: 'none',
                color: view === t.key && !showingIntegration ? 'var(--text-1)' : 'var(--text-3)',
                cursor: 'pointer', position: 'relative', zIndex: 2, transition: 'color .2s',
                whiteSpace: 'nowrap', display: 'flex', alignItems: 'center', gap: 5,
              }}>
              <Icon name={t.icon} size={13} />{t.label}
            </button>
          ))}
          <div style={{
            position: 'absolute', top: 3, height: 'calc(100% - 6px)',
            background: showingIntegration ? 'transparent' : 'var(--surface)',
            borderRadius: 4, boxShadow: showingIntegration ? 'none' : 'var(--shadow-sm)',
            transition: 'left .28s cubic-bezier(.4,0,.2,1), width .28s cubic-bezier(.4,0,.2,1), opacity .2s',
            zIndex: 1, left: pill.left, width: pill.width, opacity: showingIntegration ? 0 : 1,
          }} />
        </nav>

        {/* Active integration indicator */}
        {showingIntegration && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '4px 12px', background: 'var(--bg-3)', borderRadius: 6 }}>
            <Icon name={integrationViews.find(v => v.key === activeIntegration).icon} size={13} style={{ color: integrationViews.find(v => v.key === activeIntegration).color }} />
            <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-0)' }}>
              {integrationViews.find(v => v.key === activeIntegration).label}
            </span>
            <div onClick={() => setActiveIntegration(null)} style={{ cursor: 'pointer', marginLeft: 4, display: 'flex' }}>
              <Icon name="x" size={12} style={{ color: 'var(--text-3)' }} />
            </div>
          </div>
        )}

        <div style={{ flex: 1 }} />
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-3)' }}>{D.date} ({D.dow})</span>
        <span style={{ fontSize: 11, fontWeight: 500, color: 'var(--text-2)' }}>{D.user.name}</span>
        <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: '.06em', padding: '2px 8px', borderRadius: 3, background: 'var(--accent-soft)', color: 'var(--accent)' }}>{D.user.dept}</span>
      </div>

      {/* BODY */}
      <div style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>
        {/* LEFT SIDEBAR */}
        <div style={{ width: 220, flexShrink: 0, borderRight: '1px solid var(--border)', background: 'var(--surface)', display: 'flex', flexDirection: 'column' }}>
          <div style={{ padding: '10px 12px 6px', fontSize: 10, fontWeight: 600, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--text-3)' }}>FILES</div>
          <FileTree data={D.files} style={{ flex: 1 }} />

          {/* Integrations — clickable to switch main view */}
          <div style={{ borderTop: '1px solid var(--border-subtle)', padding: '8px 8px' }}>
            <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--text-3)', marginBottom: 6, padding: '0 4px' }}>連携 / INTEGRATIONS</div>
            {integrationViews.map(itg => {
              const isActive = activeIntegration === itg.key;
              const intData = D.integrations.find(i => i.name === itg.label);
              return (
                <div key={itg.key} onClick={() => handleIntegrationClick(itg.key)}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 6, padding: '5px 8px', borderRadius: 4,
                    cursor: 'pointer', transition: 'all .12s', marginBottom: 2,
                    background: isActive ? itg.color + '14' : 'transparent',
                    border: '1px solid ' + (isActive ? itg.color + '30' : 'transparent'),
                  }}
                  onMouseEnter={e => { if (!isActive) e.currentTarget.style.background = 'var(--bg-hover)'; }}
                  onMouseLeave={e => { if (!isActive) e.currentTarget.style.background = ''; }}>
                  <StatusDot status={intData ? intData.status : 'offline'} size={6} />
                  <Icon name={itg.icon} size={13} style={{ color: isActive ? itg.color : 'var(--text-2)' }} />
                  <span style={{ fontSize: 11, fontWeight: isActive ? 600 : 500, color: isActive ? itg.color : 'var(--text-1)', flex: 1 }}>{itg.label}</span>
                  {intData && <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--text-4)' }}>{intData.lastSync}</span>}
                </div>
              );
            })}
            {/* Local files (non-clickable, just status) */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '5px 8px', fontSize: 11, color: 'var(--text-2)' }}>
              <StatusDot status="connected" size={6} />
              <Icon name="hard-drive" size={13} />
              <span>ローカル</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--text-4)', marginLeft: 'auto' }}>常時</span>
            </div>
          </div>
        </div>

        {/* MAIN CONTENT */}
        <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
          {showingIntegration ? (
            activeIntegration === 'outlook' ? <OutlookView /> :
            activeIntegration === 'teams' ? <TeamsView /> :
            activeIntegration === 'salesforce' ? <SalesforceView /> : null
          ) : showingDetail ? (
            <TaskDetailView taskId={detailTaskId} onBack={handleBackFromDetail} />
          ) : (
            view === 'todo' ? <TodoTab onOpenDetail={handleOpenDetail} /> :
            view === 'queue' ? <QueueTab /> :
            view === 'skills' ? <SkillsTab /> :
            view === 'knowledge' ? <KnowledgeTab /> : null
          )}
        </div>

        {/* AI CHAT */}
        <div style={{ width: 280, flexShrink: 0, borderLeft: '1px solid var(--border)', background: 'var(--surface)', display: 'flex', flexDirection: 'column' }}>
          <div style={{ padding: '10px 12px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="zap" size={14} style={{ color: 'var(--accent)' }} />
            <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-0)' }}>AI Copilot</span>
            <StatusDot status="connected" size={6} />
          </div>
          <AIChatPanel messages={D.aiMessages} />
        </div>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<AppShell />);
