// ledger-mobile.jsx — auto-detecting mobile shell: top bar, bottom tab nav, FAB, More sheet

const { useState: useStateMob, useEffect: useEffectMob } = React;

// ── auto-detect: true on phone-width viewports (re-evaluates on resize/rotate) ──
// Honours an optional ?mobile=1 / localStorage('ledger.forceMobile') override so
// the phone layout can be previewed on a desktop-width screen.
function mobileForced() {
  try {
    if (/[?&]mobile=1/.test(location.search)) return true;
    return localStorage.getItem('ledger.forceMobile') === '1';
  } catch { return false; }
}
function useIsMobile(query = '(max-width: 760px)') {
  const get = () => mobileForced() || ((typeof window !== 'undefined' && window.matchMedia)
    ? window.matchMedia(query).matches : false);
  const [match, setMatch] = useStateMob(get);
  useEffectMob(() => {
    const mq = window.matchMedia(query);
    const on = () => setMatch(get());
    on();
    mq.addEventListener ? mq.addEventListener('change', on) : mq.addListener(on);
    return () => { mq.removeEventListener ? mq.removeEventListener('change', on) : mq.removeListener(on); };
  }, [query]);
  return match;
}

// ── compact month stepper used in the mobile top bar ──
function MobileMonth({ month, setMonth }) {
  const label = new Date(month + '-01').toLocaleDateString('en-GB', { month: 'short', year: 'numeric' });
  const step = (delta) => {
    const [y, m] = month.split('-').map(Number);
    const d = new Date(y, m - 1 + delta, 1);
    setMonth(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`);
  };
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 2, background: 'var(--surface-2)', borderRadius: 999, padding: 2 }}>
      <button onClick={() => step(-1)} style={mobNavBtn}><Icon name="chev" size={15} style={{ transform: 'rotate(180deg)' }} /></button>
      <span style={{ fontSize: 13, fontWeight: 500, minWidth: 78, textAlign: 'center' }}>{label}</span>
      <button onClick={() => step(1)} style={mobNavBtn}><Icon name="chev" size={15} /></button>
    </div>
  );
}
const mobNavBtn = { width: 30, height: 30, borderRadius: '50%', display: 'grid', placeItems: 'center', color: 'var(--ink-2)' };

// ── top bar ──
function MobileTopBar({ month, setMonth, search, setSearch, view }) {
  const [searchOpen, setSearchOpen] = useStateMob(false);
  const showMonth = view === 'transactions' || view === 'stats' || view === 'budgets';
  return (
    <div style={{ flexShrink: 0, background: 'var(--bg)', borderBottom: '1px solid var(--line)', paddingTop: 'env(safe-area-inset-top, 0px)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px' }}>
        <div style={{
          width: 30, height: 30, borderRadius: 8, background: 'var(--accent)', color: 'white',
          display: 'grid', placeItems: 'center', fontFamily: 'var(--font-display)', fontSize: 20, lineHeight: 1, flexShrink: 0,
        }}>£</div>
        {showMonth ? <MobileMonth month={month} setMonth={setMonth} /> : <span style={{ fontWeight: 600, fontSize: 15 }}>Ledger</span>}
        <div style={{ flex: 1 }} />
        <button onClick={() => setSearchOpen(o => !o)} style={{
          width: 38, height: 38, borderRadius: '50%', display: 'grid', placeItems: 'center',
          color: searchOpen ? 'var(--accent)' : 'var(--ink-2)', background: searchOpen ? 'var(--accent-soft)' : 'transparent',
        }}>
          <Icon name="search" size={17} />
        </button>
      </div>
      {searchOpen && (
        <div style={{ padding: '0 14px 10px', animation: 'fadeIn .12s' }}>
          <div className="field field-lg">
            <Icon name="search" size={15} style={{ color: 'var(--ink-3)', marginRight: 8 }} />
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search transactions, tags…" autoFocus />
            {search && <button onClick={() => setSearch('')} style={{ color: 'var(--ink-3)' }}><Icon name="close" size={15} /></button>}
          </div>
        </div>
      )}
    </div>
  );
}

// ── bottom tab bar ──
const MOBILE_TABS = [
  { id: 'transactions', icon: 'list',   label: 'Ledger' },
  { id: 'stats',        icon: 'stats',  label: 'Stats' },
  { id: 'budgets',      icon: 'budget', label: 'Budgets' },
  { id: 'fuel',         icon: 'fuel',   label: 'Fuel' },
  { id: 'more',         icon: 'menu',   label: 'More' },
];

function MobileTabBar({ view, setView, onMore }) {
  return (
    <nav style={{
      flexShrink: 0, display: 'flex', background: 'var(--surface)',
      borderTop: '1px solid var(--line)', paddingBottom: 'env(safe-area-inset-bottom, 0px)',
    }}>
      {MOBILE_TABS.map(t => {
        const active = t.id === 'more' ? false : view === t.id;
        return (
          <button key={t.id} onClick={() => t.id === 'more' ? onMore() : setView(t.id)} style={{
            flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
            padding: '9px 0 7px', minHeight: 56,
            color: active ? 'var(--accent)' : 'var(--ink-3)',
          }}>
            <Icon name={t.icon} size={21} strokeWidth={active ? 1.9 : 1.6} />
            <span style={{ fontSize: 10.5, fontWeight: active ? 600 : 500 }}>{t.label}</span>
          </button>
        );
      })}
    </nav>
  );
}

// ── floating action button ──
function MobileFab({ onClick }) {
  return (
    <button onClick={onClick} aria-label="New transaction" style={{
      position: 'fixed', right: 18, zIndex: 40,
      bottom: 'calc(64px + env(safe-area-inset-bottom, 0px) + 14px)',
      width: 56, height: 56, borderRadius: '50%',
      background: 'var(--accent)', color: 'white',
      display: 'grid', placeItems: 'center',
      boxShadow: '0 8px 24px -6px oklch(0.62 0.13 38 / .55), 0 2px 6px rgba(40,30,20,.2)',
    }}>
      <Icon name="plus" size={24} strokeWidth={2} />
    </button>
  );
}

// ── "More" bottom sheet: everything that didn't fit the 5 tabs ──
function MobileMoreSheet({
  user, categories, categoryFilter, onPickCategory, recurringCount,
  storageMode, cloudSync, isAdmin,
  onRecurring, onAdmin, onAccount, onVehicle, onExport, onResetDemo, onClearData, onSignOut, onClose,
}) {
  const Row = ({ icon, label, sub, onClick, danger }) => (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 14, width: '100%',
      padding: '14px 4px', borderBottom: '1px solid var(--line)', textAlign: 'left',
      color: danger ? 'var(--neg)' : 'var(--ink)', minHeight: 52,
    }}>
      <span style={{ width: 34, height: 34, borderRadius: 9, background: danger ? 'oklch(0.95 0.04 28)' : 'var(--surface-2)', color: danger ? 'var(--neg)' : 'var(--ink-2)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
        <Icon name={icon} size={17} />
      </span>
      <span style={{ flex: 1 }}>
        <div style={{ fontSize: 14.5, fontWeight: 500 }}>{label}</div>
        {sub && <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 1 }}>{sub}</div>}
      </span>
      <Icon name="chev" size={15} style={{ color: 'var(--ink-4)' }} />
    </button>
  );

  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(40,30,20,.25)', backdropFilter: 'blur(2px)', zIndex: 55, animation: 'fadeIn .15s' }} />
      <div style={{
        position: 'fixed', left: 0, right: 0, bottom: 0, top: 'env(safe-area-inset-top, 0px)',
        background: 'var(--bg)', borderTopLeftRadius: 18, borderTopRightRadius: 18,
        zIndex: 56, display: 'flex', flexDirection: 'column',
        animation: 'sheetUp .26s cubic-bezier(.2,.7,.3,1)', boxShadow: 'var(--shadow-lg)',
      }}>
        {/* grabber + header */}
        <div style={{ padding: '10px 18px 8px', borderBottom: '1px solid var(--line)' }}>
          <div style={{ width: 38, height: 4, borderRadius: 999, background: 'var(--line-2)', margin: '0 auto 12px' }} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span className="cglyph cglyph-lg" style={{ background: 'var(--ink)', color: 'var(--bg)', fontSize: 16 }}>
              {(user?.username || '?')[0].toUpperCase()}
            </span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 15, fontWeight: 600 }}>@{user?.username}</div>
              <StorageIndicator mode={storageMode} sync={cloudSync} />
            </div>
            <button className="btn ghost icon" onClick={onClose}><Icon name="close" size={18} /></button>
          </div>
        </div>

        <div style={{ flex: 1, overflow: 'auto', padding: '4px 18px 24px' }}>
          {/* Category filter */}
          <div className="micro" style={{ padding: '14px 0 8px' }}>Filter by category</div>
          <div style={{ display: 'flex', gap: 7, overflowX: 'auto', paddingBottom: 6, margin: '0 -18px', padding: '0 18px 6px' }}>
            <button onClick={() => onPickCategory(null)} className={`chip ${categoryFilter == null ? 'on' : ''}`} style={{ flexShrink: 0, padding: '7px 14px' }}>All</button>
            {categories.filter(c => c.kind === 'out').map(c => (
              <button key={c.id} onClick={() => onPickCategory(c.id)} className={`chip ${categoryFilter === c.id ? 'on' : ''}`} style={{ flexShrink: 0, padding: '7px 12px' }}>
                <span style={{ fontSize: 13 }}>{c.icon}</span> {c.name}
              </button>
            ))}
          </div>

          <div className="micro" style={{ padding: '18px 0 2px' }}>Manage</div>
          <Row icon="repeat"   label="Recurring" sub={`${recurringCount} scheduled`} onClick={onRecurring} />
          <Row icon="fuel"     label="Vehicle & odometer" sub="Starting odometer, distance unit" onClick={onVehicle} />
          <Row icon="export"   label="Export all as CSV" onClick={onExport} />
          {isAdmin && <Row icon="settings" label="Admin" sub="Manage all accounts" onClick={onAdmin} />}

          <div className="micro" style={{ padding: '18px 0 2px' }}>Account</div>
          <Row icon="settings" label="Username & password" onClick={onAccount} />
          <Row icon="repeat"   label="Reset to demo data" onClick={onResetDemo} />
          <Row icon="trash"    label="Clear all data…" onClick={onClearData} danger />
          <Row icon="close"    label="Sign out" onClick={onSignOut} />

          <div style={{ textAlign: 'center', marginTop: 18, fontSize: 11, color: 'var(--ink-4)' }} className="mono">Ledger · v0.2</div>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { useIsMobile, MobileTopBar, MobileTabBar, MobileFab, MobileMoreSheet, MobileMonth });
