// 米樂家戰情室 Tweaks panel app

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "autoRotate": true,
  "rotateInterval": 17,
  "showLiveDot": true
}/*EDITMODE-END*/;

const TAB_BAR_STYLE = {
  display: 'flex',
  background: 'rgba(0,0,0,0.06)',
  borderRadius: 9,
  padding: 3,
  gap: 3,
  marginBottom: 2,
};
function tabBtnStyle(active) {
  return {
    flex: 1, padding: '6px 0', fontSize: 11.5, borderRadius: 6, border: 'none',
    background: active ? '#D97A3B' : 'transparent',
    color: active ? '#fff' : 'rgba(41,38,27,0.6)',
    fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
    transition: 'all 150ms', letterSpacing: '0.01em',
  };
}

function ImportTabBody({ onOpen }) {
  const [history, setHistory] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('mile_import_history') || '[]'); }
    catch { return []; }
  });
  React.useEffect(() => {
    const refresh = () => {
      try { setHistory(JSON.parse(localStorage.getItem('mile_import_history') || '[]')); }
      catch {}
    };
    window.addEventListener('mileDataImported', refresh);
    return () => window.removeEventListener('mileDataImported', refresh);
  }, []);
  const last = history[0];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      <button style={{ background: 'linear-gradient(135deg,#D97A3B,#B85F26)', color: '#fff', border: 'none', borderRadius: 10, padding: '13px 0', fontSize: 13.5, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', width: '100%', boxShadow: '0 2px 8px rgba(185,95,38,.35)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7 }} onClick={onOpen}>
        <span style={{ fontSize: 16 }}>📥</span> 開啟報表上傳工作台
      </button>
      <div style={{ fontSize: 10.5, color: 'rgba(41,38,27,0.5)', textAlign: 'center', lineHeight: 1.5 }}>
        支援 .xlsx · .xls · .csv　· AI 自動辨識欄位
      </div>
      {last ? (
        <div style={{ background: '#fff', border: '1px solid #E4D8C2', borderRadius: 9, padding: '10px 12px', fontSize: 11.5 }}>
          <div style={{ fontWeight: 700, color: 'rgba(41,38,27,0.55)', fontSize: 10, letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 6 }}>上次匯入</div>
          <div style={{ fontWeight: 700, fontSize: 12.5, marginBottom: 3 }}>{last.target}</div>
          <div style={{ color: '#6E5A48', lineHeight: 1.6 }}>{last.filename}<br/>{last.row_count} 筆 · {new Date(last.timestamp).toLocaleString('zh-TW', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })}</div>
          {last.summary && <div style={{ marginTop: 7, padding: '6px 10px', background: '#FFF8E8', borderRadius: 6, fontSize: 11, color: '#8C6610', lineHeight: 1.5 }}>{last.summary}</div>}
        </div>
      ) : (
        <div style={{ background: '#F5E8D0', borderRadius: 9, padding: '12px', fontSize: 11, color: 'rgba(41,38,27,0.55)', textAlign: 'center', lineHeight: 1.6 }}>
          尚無匯入紀錄<br/>每日上傳報表後，戰情室各頁<br/>將自動更新為實際數據
        </div>
      )}
      <div style={{ background: 'rgba(0,0,0,0.03)', borderRadius: 8, padding: '8px 10px', fontSize: 10.5, color: 'rgba(41,38,27,0.55)', lineHeight: 1.8 }}>
        <div style={{ fontWeight: 700, marginBottom: 3, color: 'rgba(41,38,27,0.7)' }}>📋 可識別報表類型</div>
        💰 每日營業額 · 🚛 司機績效<br/>📈 業務開發 · 💵 未收款 · 📦 採購<br/>🚨 庫存警示 · 👥 出勤 · 📢 公告…
      </div>
    </div>
  );
}

function MileRoomTweaks() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [importOpen, setImportOpen] = React.useState(false);
  const [activeTab, setActiveTab] = React.useState('settings');

  React.useEffect(() => {
    if (window.__rotate) {
      window.__rotate.enabled = t.autoRotate;
      window.__rotate.interval = t.rotateInterval;
    }
  }, [t.autoRotate, t.rotateInterval]);

  React.useEffect(() => {
    if (window.__rotate) window.__rotate.paused = importOpen;
  }, [importOpen]);

  React.useEffect(() => {
    const open = () => { setActiveTab('import'); setImportOpen(true); };
    window.addEventListener('mileOpenImport', open);
    return () => window.removeEventListener('mileOpenImport', open);
  }, []);

  function switchToImport() {
    setActiveTab('import');
    setImportOpen(true);
  }

  const DI = window.__DataImportModal;

  return (
    <React.Fragment>
      <TweaksPanel title="戰情室控制">
        <div style={TAB_BAR_STYLE}>
          <button style={tabBtnStyle(activeTab === 'settings')} onClick={() => setActiveTab('settings')}>⚙️ 設定</button>
          <button style={tabBtnStyle(activeTab === 'import')} onClick={switchToImport}>📊 報表匯入</button>
        </div>

        {activeTab === 'settings' && (
          <React.Fragment>
            <TweakSection label="自動輪播" />
            <TweakToggle label="啟用自動輪播" value={t.autoRotate} onChange={(v) => setTweak('autoRotate', v)} />
            <TweakSlider label="每頁停留" value={t.rotateInterval} min={5} max={45} step={1} unit="秒" onChange={(v) => setTweak('rotateInterval', v)} />
            <TweakSection label="顯示" />
            <TweakToggle label="顯示連線指示燈" value={t.showLiveDot} onChange={(v) => { setTweak('showLiveDot', v); document.documentElement.style.setProperty('--live-dot-display', v ? 'inline-block' : 'none'); }} />
            <TweakSection label="導覽" />
            <TweakButton label="跳到第一頁" onClick={() => document.querySelector('deck-stage').goTo(0)} />
            <TweakButton label="下一頁" onClick={() => document.querySelector('deck-stage').next()} />
          </React.Fragment>
        )}

        {activeTab === 'import' && (
          <ImportTabBody onOpen={() => setImportOpen(true)} />
        )}
      </TweaksPanel>

      {DI && <DI open={importOpen} onClose={() => setImportOpen(false)} />}
    </React.Fragment>
  );
}

const __tweakRoot = document.getElementById('tweaks-root');
ReactDOM.createRoot(__tweakRoot).render(<MileRoomTweaks />);
