// ============================================================
// App shell — left nav + state tabs + stage + spec panel
// ============================================================

const { useState: useStateApp, useEffect: useEffectApp } = React;

// Variant order in tabs
const STATE_KEYS = [
  ['happy',     'Happy path'],
  ['empty',     'Empty'],
  ['single',    '單筆'],
  ['multi',     '多筆 (carousel)'],
  ['overflow',  '超過上限'],
  ['error',     'API 錯誤'],
  ['ambiguous', '歧義 / 模糊匹配'],
];

window.App = function App() {
  const SCENARIOS = window.SCENARIOS;
  const [scenarioId, setScenarioId] = useStateApp(SCENARIOS[0].id);
  const [stateKey, setStateKey] = useStateApp('happy');
  const [viewMode, setViewMode] = useStateApp('chat'); // chat | bare
  const [actionLog, setActionLog] = useStateApp(null);

  const scenario = SCENARIOS.find((s) => s.id === scenarioId);
  const variant = scenario.variants[stateKey] || scenario.variants.happy;

  useEffectApp(() => { setStateKey('happy'); }, [scenarioId]);

  const handleAction = (action) => {
    setActionLog({ ts: Date.now(), action });
    setTimeout(() => setActionLog(null), 2400);
  };

  const groups = groupScenarios(SCENARIOS);

  return (
    <div className="app">
      <header className="topbar">
        <span className="topbar__title">finfo LINE AI 助手 · <span className="accent">Flex Message Wireframes</span></span>
        <span className="topbar__meta">10 情境 × 7 狀態 · v0.1 draft</span>
        <div className="topbar__right">
          <div className="view-toggle">
            <button className={viewMode === 'chat' ? 'is-active' : ''} onClick={() => setViewMode('chat')}>聊天框</button>
            <button className={viewMode === 'bare' ? 'is-active' : ''} onClick={() => setViewMode('bare')}>單獨 bubble</button>
          </div>
        </div>
      </header>

      <nav className="nav">
        {groups.map((g) => (
          <React.Fragment key={g.label}>
            <div className="nav__group-label">{g.label}</div>
            {g.items.map((s) => (
              <div
                key={s.id}
                className={`nav__item ${s.id === scenarioId ? 'is-active' : ''}`}
                onClick={() => setScenarioId(s.id)}
              >
                <span className="nav__item-num">{String(s.num).padStart(2, '0')}</span>
                <span className="nav__item-label">
                  <span className="nav__item-label-zh">{s.titleZh}</span>
                  <span className="nav__item-label-en">「{s.prompt}」</span>
                </span>
              </div>
            ))}
          </React.Fragment>
        ))}
      </nav>

      <main className="stage">
        <div className="stage__head">
          <div className="stage__crumbs">
            {scenario.group} · 情境 {String(scenario.num).padStart(2, '0')}
          </div>
          <div className="stage__title">{scenario.titleZh}</div>
          <div className="stage__prompt">{variant.userPrompt || scenario.prompt}</div>
          <div className="state-tabs">
            {STATE_KEYS.map(([k, label]) => {
              const exists = !!scenario.variants[k];
              if (!exists) return null;
              return (
                <button
                  key={k}
                  className={`state-tab state-tab--${k} ${stateKey === k ? 'is-active' : ''}`}
                  onClick={() => setStateKey(k)}
                >
                  <span className="state-tab__dot" />
                  {scenario.variants[k].label || label}
                </button>
              );
            })}
          </div>
        </div>
        <div className="stage__body">
          {viewMode === 'chat' ? (
            <window.ChatFrame
              userPrompt={variant.userPrompt || scenario.prompt}
              bubbles={[
                ...(variant.preface ? [{ kind: 'text', text: variant.preface }] : []),
                { kind: 'flex', node: variant.node, label: variant.label },
              ]}
              onAction={handleAction}
            />
          ) : (
            <window.BareStage
              userPrompt={variant.userPrompt || scenario.prompt}
              node={variant.node}
              onAction={handleAction}
            />
          )}
        </div>

        {actionLog && (
          <div style={{
            position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)',
            background: '#23262d', border: '1px solid #ffa73b',
            color: '#ffffff', padding: '10px 14px', borderRadius: 6, fontSize: 12,
            fontFamily: 'ui-monospace, monospace', zIndex: 9999,
            boxShadow: '0 6px 24px rgba(0,0,0,0.4)',
            maxWidth: 560, wordBreak: 'break-all',
          }}>
            <span style={{ color: '#ffc072', fontWeight: 600 }}>action triggered →</span>{' '}
            type=<b>{actionLog.action.type}</b>{' '}
            {actionLog.action.data && (<>data=<code style={{ color: '#8fdabf' }}>{actionLog.action.data}</code></>)}
            {actionLog.action.uri && (<>uri=<code style={{ color: '#8fdabf' }}>{actionLog.action.uri}</code></>)}
            {actionLog.action.text && (<>text=<code style={{ color: '#8fdabf' }}>"{actionLog.action.text}"</code></>)}
          </div>
        )}
      </main>

      <window.SpecPanel variant={variant} scenario={scenario} />
    </div>
  );
};

function groupScenarios(list) {
  const groups = {};
  list.forEach((s) => {
    if (!groups[s.group]) groups[s.group] = { label: s.group, items: [] };
    groups[s.group].items.push(s);
  });
  return Object.values(groups);
}
