// Tabi — language selection & menu history additions

const TABI_LANGS = [
  { code: 'JA', name: '日本語',     zh: '日文', flag: '🇯🇵' },
  { code: 'EN', name: 'English',    zh: '英文', flag: '🇬🇧' },
  { code: 'KO', name: '한국어',     zh: '韓文', flag: '🇰🇷' },
  { code: 'TH', name: 'ภาษาไทย',   zh: '泰文', flag: '🇹🇭' },
  { code: 'VI', name: 'Tiếng Việt', zh: '越南文', flag: '🇻🇳' },
  { code: 'FR', name: 'Français',   zh: '法文', flag: '🇫🇷' },
  { code: 'ES', name: 'Español',    zh: '西班牙文', flag: '🇪🇸' },
  { code: 'IT', name: 'Italiano',   zh: '義大利文', flag: '🇮🇹' },
  { code: 'DE', name: 'Deutsch',    zh: '德文', flag: '🇩🇪' },
];

// Compact language pill — clickable, opens picker sheet
function TabiLangPill({ from = 'JA', to = 'ZH', onClick, small }) {
  return (
    <button onClick={onClick} style={{
      fontSize: small ? 10.5 : 11,
      padding: small ? '5px 9px' : '6px 11px',
      borderRadius: 999,
      border: `1px solid ${TABI_COLORS.line2}`,
      background: 'transparent', color: TABI_COLORS.ink2,
      cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6,
      fontWeight: 600,
    }}>
      <span>{from}</span>
      <span style={{ opacity: 0.5 }}>→</span>
      <span>{to}</span>
      <span style={{ opacity: 0.4, fontSize: 9 }}>▾</span>
    </button>
  );
}

// Bottom-sheet language picker
function TabiLangSheet({ open, current, onSelect, onClose }) {
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.4)',
      zIndex: 100, display: 'flex', alignItems: 'flex-end',
      animation: 'tabiFade 0.2s ease',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', background: TABI_COLORS.bg, borderRadius: '20px 20px 0 0',
        padding: '12px 0 28px', maxHeight: '78%', overflow: 'auto',
      }}>
        <div style={{
          width: 36, height: 4, borderRadius: 2, background: TABI_COLORS.line2,
          margin: '6px auto 14px',
        }}/>
        <div style={{ padding: '0 20px 12px' }}>
          <div style={{
            fontFamily: tabiSerif, fontSize: 18, fontWeight: 600, color: TABI_COLORS.ink,
          }}>選擇翻譯語言</div>
          <div style={{ fontSize: 11, color: TABI_COLORS.ink3, marginTop: 2 }}>
            從中文翻譯到 / Translate Chinese to
          </div>
        </div>
        <div>
          {TABI_LANGS.map(l => {
            const on = l.code === current;
            return (
              <button key={l.code} onClick={() => { onSelect(l.code); onClose(); }} style={{
                width: '100%', border: 'none', cursor: 'pointer', textAlign: 'left',
                background: on ? `${TABI_COLORS.red}10` : 'transparent',
                padding: '14px 20px', display: 'flex', alignItems: 'center', gap: 14,
              }}>
                <span style={{ fontSize: 22 }}>{l.flag}</span>
                <div style={{ flex: 1 }}>
                  <div style={{
                    fontFamily: tabiSerif, fontSize: 15, fontWeight: 600,
                    color: TABI_COLORS.ink,
                  }}>{l.zh}</div>
                  <div style={{ fontSize: 11, color: TABI_COLORS.ink3, marginTop: 1 }}>
                    {l.name} · {l.code}
                  </div>
                </div>
                {on && (
                  <span style={{
                    width: 22, height: 22, borderRadius: 11, background: TABI_COLORS.red,
                    color: '#fff', display: 'grid', placeItems: 'center',
                  }}><CheckIcon size={12}/></span>
                )}
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function _fmtDate(iso) {
  const d = new Date(iso);
  const now = new Date();
  const diffDays = Math.floor((now - d) / 86400000);
  const hhmm = d.toLocaleTimeString('zh-TW', { hour: '2-digit', minute: '2-digit', hour12: false });
  if (diffDays === 0) return `今天 ${hhmm}`;
  if (diffDays === 1) return `昨天 ${hhmm}`;
  return `${d.getMonth()+1}/${d.getDate()} ${hhmm}`;
}

// ─────────── MENU HISTORY ───────────
function MenuHistoryScreen({ go, onOpen }) {
  const [list, setList]       = React.useState(null);
  const [confirmDel, setConfirmDel] = React.useState(null);
  const [deleting, setDeleting]     = React.useState(false);

  const load = () => {
    fetch('/api/menus', { headers: { Authorization: `Bearer ${window.tabiToken()}` } })
      .then(r => r.json())
      .then(data => setList(Array.isArray(data) ? data : []))
      .catch(() => setList([]));
  };

  React.useEffect(() => { load(); }, []);

  const remove = async (id) => {
    setDeleting(true);
    await fetch(`/api/menus/${id}`, {
      method: 'DELETE',
      headers: { Authorization: `Bearer ${window.tabiToken()}` },
    }).catch(() => {});
    setDeleting(false);
    setConfirmDel(null);
    load();
  };

  const COVER_PALETTES = [
    ['#E8C794','#D9A441','#C8553D'],
    ['#3B5A7A','#5B7553','#A0412F'],
    ['#5B7553','#8C6F4A','#D9A441'],
    ['#A0412F','#C8553D','#E8C794'],
    ['#8C6F4A','#3B5A7A','#5B7553'],
  ];

  return (
    <div style={{ background: TABI_COLORS.bg, minHeight: '100%', position: 'relative' }}>
      <TabiTopBar
        title="菜單紀錄"
        subtitle="HISTORY · 過去のメニュー"
        onBack={() => go('home')}
        right={
          <button onClick={() => go('camera')} style={{
            padding: '7px 12px', borderRadius: 12, border: 'none', cursor: 'pointer',
            background: TABI_COLORS.ink, color: '#fff', fontSize: 11.5, fontWeight: 600,
            display: 'inline-flex', alignItems: 'center', gap: 5,
          }}>
            <CameraIcon size={13} active /> 拍新菜單
          </button>
        }
      />

      <div style={{ padding: '14px 16px 30px' }}>
        {list === null ? (
          <div style={{ display: 'flex', justifyContent: 'center', padding: '60px 0', color: TABI_COLORS.ink3 }}>
            <div style={{ width: 28, height: 28, borderRadius: 14, border: `2px solid ${TABI_COLORS.line2}`, borderTopColor: TABI_COLORS.red, animation: 'tabiSpin 0.8s linear infinite' }}/>
          </div>
        ) : list.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '60px 20px', color: TABI_COLORS.ink3 }}>
            <div style={{ fontSize: 38, marginBottom: 8 }}>🍱</div>
            <div style={{ fontSize: 13 }}>還沒有儲存的菜單</div>
            <button onClick={() => go('camera')} style={{
              marginTop: 16, padding: '10px 18px', borderRadius: 12, border: 'none',
              background: TABI_COLORS.red, color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer',
            }}>拍第一張菜單</button>
          </div>
        ) : (
          <>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, padding: '4px 4px 10px' }}>
              <div style={{ fontFamily: tabiSerif, fontSize: 22, fontWeight: 700, color: TABI_COLORS.ink }}>{list.length}</div>
              <div style={{ fontSize: 11.5, color: TABI_COLORS.ink3 }}>張已儲存的菜單</div>
            </div>

            {list.map((h, idx) => {
              const cover = COVER_PALETTES[idx % COVER_PALETTES.length];
              return (
                <div key={h.id} style={{
                  background: TABI_COLORS.card, borderRadius: 16, padding: '12px',
                  marginTop: 10, display: 'flex', gap: 12, alignItems: 'center',
                  border: `1px solid ${TABI_COLORS.line}`,
                }}>
                  <div onClick={() => onOpen(h.id)} style={{
                    width: 64, height: 64, borderRadius: 12, overflow: 'hidden',
                    flexShrink: 0, background: TABI_COLORS.line2, cursor: 'pointer',
                    position: 'relative',
                  }}>
                    {h.image_url ? (
                      <img src={h.image_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                    ) : (
                      <div style={{
                        width: '100%', height: '100%',
                        background: `linear-gradient(135deg, ${cover[0]}, ${cover[2]})`,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                      }}>
                        <span style={{
                          fontFamily: tabiSerif, fontWeight: 700,
                          fontSize: (h.name || '').length > 4 ? 16 : 20,
                          color: 'rgba(255,255,255,0.92)',
                          textShadow: '0 1px 6px rgba(0,0,0,0.25)',
                          letterSpacing: '-0.01em', textAlign: 'center',
                          padding: '0 4px', lineHeight: 1.2,
                        }}>
                          {(h.name || '?').slice(0, 4)}
                        </span>
                      </div>
                    )}
                  </div>

                  <div onClick={() => onOpen(h.id)} style={{ flex: 1, minWidth: 0, cursor: 'pointer' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <span style={{
                        fontSize: 9.5, fontWeight: 700, padding: '2px 6px', borderRadius: 5,
                        background: `${TABI_COLORS.red}18`, color: TABI_COLORS.red,
                      }}>{h.source_lang}→ZH</span>
                    </div>
                    <div style={{ fontFamily: tabiSerif, fontSize: 14.5, fontWeight: 600, color: TABI_COLORS.ink, marginTop: 4 }}>
                      {h.name}
                    </div>
                    <div style={{ fontSize: 11, color: TABI_COLORS.ink3, marginTop: 2 }}>
                      {_fmtDate(h.created_at)}
                    </div>
                  </div>

                  <button onClick={() => setConfirmDel(h.id)} style={{
                    width: 32, height: 32, borderRadius: 16, border: 'none', cursor: 'pointer',
                    background: 'transparent', color: TABI_COLORS.ink3, display: 'grid', placeItems: 'center',
                  }}>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M3 6h18M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2M6 6l1 14a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1l1-14M10 11v6M14 11v6"/>
                    </svg>
                  </button>
                </div>
              );
            })}
          </>
        )}
      </div>

      {confirmDel && (
        <div onClick={() => setConfirmDel(null)} style={{
          position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)',
          zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
        }}>
          <div onClick={e => e.stopPropagation()} style={{
            background: TABI_COLORS.bg, borderRadius: 18, padding: '22px', width: '100%', maxWidth: 280,
          }}>
            <div style={{ fontFamily: tabiSerif, fontSize: 16, fontWeight: 600, color: TABI_COLORS.ink }}>刪除這份菜單？</div>
            <div style={{ fontSize: 12, color: TABI_COLORS.ink3, marginTop: 6, lineHeight: 1.5 }}>
              刪除後將無法復原。
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
              <button onClick={() => setConfirmDel(null)} style={{
                flex: 1, padding: '11px', borderRadius: 12, border: `1px solid ${TABI_COLORS.line2}`,
                background: 'transparent', color: TABI_COLORS.ink, fontSize: 13, fontWeight: 600, cursor: 'pointer',
              }}>取消</button>
              <button onClick={() => remove(confirmDel)} disabled={deleting} style={{
                flex: 1, padding: '11px', borderRadius: 12, border: 'none',
                background: TABI_COLORS.red, color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer',
              }}>{deleting ? '刪除中…' : '刪除'}</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, {
  TABI_LANGS, TabiLangPill, TabiLangSheet, MenuHistoryScreen,
});
