/* mobile.jsx — mobile-only components and helpers.
   Bottom tab bar, "Mer" screen (member switcher + account), useIsMobile hook.
   Desktop is unaffected; these render but the CSS hides them above 768px. */
/* global React, MEMBERS, Avatar, Eyebrow */
const { useState, useEffect } = React;

// Match the mobile.css breakpoint (≤768px)
function useIsMobile() {
  const [m, setM] = useState(() =>
    typeof window !== 'undefined' && window.matchMedia('(max-width: 768px)').matches
  );
  useEffect(() => {
    const mq = window.matchMedia('(max-width: 768px)');
    const h = (e) => setM(e.matches);
    mq.addEventListener('change', h);
    return () => mq.removeEventListener('change', h);
  }, []);
  return m;
}

// ----------------------------------------------------------------------------
// BottomNav — four tabs, sticky to bottom, only visible on mobile (via CSS)
// ----------------------------------------------------------------------------
function BottomNav({ route, setRoute }) {
  const tabs = [
    { id: 'dash',   label: 'Idag',  icon: 'home' },
    { id: 'tester', label: 'Tester',icon: 'target' },
    { id: 'logg',   label: 'Logg',  icon: 'calendar' },
    { id: 'mer',    label: 'Mer',   icon: 'menu' },
  ];
  return (
    <nav className="mt-bottom-nav" aria-label="Huvudnavigering">
      {tabs.map(t => (
        <button key={t.id} data-active={route === t.id} onClick={() => setRoute(t.id)}>
          <Icon name={t.icon} />
          <span>{t.label}</span>
        </button>
      ))}
    </nav>
  );
}

function Icon({ name }) {
  const common = { fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (name) {
    case 'home':
      return <svg viewBox="0 0 24 24" {...common}><path d="M3 11l9-8 9 8"/><path d="M5 10v10h14V10"/></svg>;
    case 'target':
      return <svg viewBox="0 0 24 24" {...common}><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="5"/><circle cx="12" cy="12" r="1.5" fill="currentColor"/></svg>;
    case 'calendar':
      return <svg viewBox="0 0 24 24" {...common}><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 9h18M8 3v4M16 3v4"/></svg>;
    case 'menu':
      return <svg viewBox="0 0 24 24" {...common}><line x1="4" y1="7"  x2="20" y2="7"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="17" x2="20" y2="17"/></svg>;
    default: return null;
  }
}

// ----------------------------------------------------------------------------
// MerScreen — mobile-only landing for "Mer". Member switcher (grouped by
// family) + account + logout. Desktop never routes here.
// ----------------------------------------------------------------------------
function MerScreen({ activeId, setActiveId, session }) {
  // Group members by family — same logic as the topbar dropdown
  const groups = {};
  for (const m of MEMBERS) {
    const key = m.familyName || 'Familj';
    (groups[key] ||= { members: [], isMine: !!m.isMyFamily });
    groups[key].members.push(m);
  }
  const entries = Object.entries(groups);
  entries.sort((a, b) => {
    if (a[1].isMine && !b[1].isMine) return -1;
    if (!a[1].isMine && b[1].isMine) return 1;
    return a[0].localeCompare(b[0], 'sv');
  });

  const me = MEMBERS.find(m => m.id === window.MY_MEMBER_ID);

  const logout = async () => {
    if (!confirm('Logga ut?')) return;
    await window.sb.auth.signOut();
  };

  return (
    <div style={{ padding: '24px 16px 24px', maxWidth: 720, margin: '0 auto', fontFamily: 'var(--font-sans)' }}>
      <Eyebrow style={{ marginBottom: 6 }}>Mer</Eyebrow>
      <h1 style={{ margin: 0, fontSize: 28, fontWeight: 500, letterSpacing: '-0.02em', marginBottom: 18 }}>
        Inställningar
      </h1>

      {/* Active member */}
      <div style={{ border: '1px solid var(--border)', borderRadius: 'var(--radius-2)', overflow: 'hidden', background: 'var(--bg-raised)', marginBottom: 18 }}>
        <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--border-faint)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <Eyebrow>Aktiv medlem</Eyebrow>
          {me && activeId !== me.id && (
            <button
              onClick={() => setActiveId(me.id)}
              style={{
                fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 500,
                padding: '4px 10px', borderRadius: 4,
                border: '1px solid var(--signal)', background: 'var(--signal-tint)',
                color: 'var(--signal)', cursor: 'pointer',
              }}
            >Tillbaka till {me.name}</button>
          )}
        </div>

        {entries.map(([famName, g]) => (
          <div key={famName}>
            <div style={{ padding: '10px 16px 4px', background: 'var(--ink-25)' }}>
              <Eyebrow>{g.isMine ? `${famName} · min familj` : famName}</Eyebrow>
            </div>
            {g.members.map(m => {
              const sel = m.id === activeId;
              return (
                <button
                  key={m.id}
                  onClick={() => setActiveId(m.id)}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 12, width: '100%',
                    padding: '12px 16px', background: sel ? 'var(--signal-tint)' : 'transparent',
                    border: 'none', borderTop: '1px solid var(--border-faint)',
                    cursor: 'pointer', textAlign: 'left', fontFamily: 'var(--font-sans)',
                  }}
                >
                  <Avatar member={m} size={32} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 15, fontWeight: 500 }}>{m.name}</div>
                    <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--fg-subtle)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>
                      {m.role} · {m.age} år
                    </div>
                  </div>
                  {sel && (
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--signal)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                      <polyline points="20 6 9 17 4 12" />
                    </svg>
                  )}
                </button>
              );
            })}
          </div>
        ))}
      </div>

      {/* Account */}
      <div style={{ border: '1px solid var(--border)', borderRadius: 'var(--radius-2)', overflow: 'hidden', background: 'var(--bg-raised)' }}>
        <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--border-faint)' }}>
          <Eyebrow>Konto</Eyebrow>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-muted)', marginTop: 4, wordBreak: 'break-all' }}>
            {session?.user?.email || '—'}
          </div>
        </div>
        <button
          onClick={logout}
          style={{
            display: 'flex', alignItems: 'center', gap: 10, width: '100%',
            padding: '14px 16px', background: 'transparent', border: 'none',
            cursor: 'pointer', textAlign: 'left',
            fontFamily: 'var(--font-sans)', fontSize: 14, color: 'var(--danger)',
          }}
        >
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
            <polyline points="16 17 21 12 16 7" />
            <line x1="21" y1="12" x2="9" y2="12" />
          </svg>
          Logga ut
        </button>
      </div>

      <div style={{ marginTop: 24, fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-subtle)', textAlign: 'center', letterSpacing: '0.04em' }}>
        Familjeträning · {window.getActiveSeason ? window.getActiveSeason().name : ''}
      </div>
    </div>
  );
}

window.BottomNav = BottomNav;
window.MerScreen = MerScreen;
window.useIsMobile = useIsMobile;
