// Shell + Settings + iOS frame + tab bar.
const { useState: useStateS, useEffect: useEffectS } = React;

const SettingsTab = () => {
  const rows = [
    { grp: 'SHOP', items: [
      { k: 'Shop details', v: 'The Fone Shop, Longton' },
      { k: 'Hours', v: 'Mon–Fri 10–6 · Sat 10–4' },
      { k: 'Payment methods', v: 'Card · Cash · Apple Pay' },
    ]},
    { grp: 'AUTOMATIONS', items: [
      { k: 'Ready SMS template', v: 'Edit →' },
      { k: 'Review request', v: 'Auto-send 48h after collection' },
      { k: 'Low-stock alerts', v: 'On · 3 SKUs below min' },
    ]},
    { grp: 'STAFF & ACCESS', items: [
      { k: 'Team', v: '2 members' },
      { k: 'Roles', v: 'Owner · Technician' },
    ]},
    { grp: 'EXPORT', items: [
      { k: 'Weekly P&L', v: 'Email me Mondays' },
      { k: 'Export all bookings', v: 'CSV →' },
    ]},
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {rows.map(g => (
        <div key={g.grp}>
          <Eyebrow>{g.grp}</Eyebrow>
          <div style={{ marginTop: 8, background: '#0a0a0a', border: '1px solid #1a1a1a', borderRadius: 12, overflow: 'hidden' }}>
            {g.items.map((it, i) => (
              <button key={it.k} style={{
                width: '100%', padding: '14px 14px',
                background: 'transparent', border: 0, color: 'inherit',
                borderTop: i ? '1px solid #1a1a1a' : 0,
                display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10,
                cursor: 'pointer', textAlign: 'left',
              }}>
                <span style={{ fontSize: 14 }}>{it.k}</span>
                <span style={{ fontSize: 12.5, color: '#86868b' }}>{it.v} <span style={{ color: '#3a3a3c', marginLeft: 4 }}>›</span></span>
              </button>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
};

// ---- TAB BAR ----
const TABS = [
  { k: 'leads',    label: 'Leads',    icon: (c) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.7 21a2 2 0 0 1-3.4 0"/></svg> },
  { k: 'bookings', label: 'Bookings', icon: (c) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg> },
  { k: 'shop',     label: 'Shop',     icon: (c) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9l1-5h16l1 5"/><path d="M4 9v11h16V9"/><path d="M9 14h6"/></svg> },
  { k: 'settings', label: 'Settings', icon: (c) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.6 1.6 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.6 1.6 0 0 0-1.8-.3 1.6 1.6 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.6 1.6 0 0 0-1-1.5 1.6 1.6 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.6 1.6 0 0 0 .3-1.8 1.6 1.6 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.6 1.6 0 0 0 1.5-1 1.6 1.6 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.6 1.6 0 0 0 1.8.3h0a1.6 1.6 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.6 1.6 0 0 0 1 1.5 1.6 1.6 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.6 1.6 0 0 0-.3 1.8v0a1.6 1.6 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.6 1.6 0 0 0-1.5 1z"/></svg> },
];

const TabBar = ({ active, onChange }) => (
  <nav style={{
    position: 'absolute', left: 0, right: 0, bottom: 0,
    paddingBottom: 28, paddingTop: 6,
    background: 'rgba(0,0,0,0.72)',
    backdropFilter: 'blur(30px)',
    borderTop: '1px solid #1a1a1a',
    display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
    zIndex: 20,
  }}>
    {TABS.map(t => {
      const isActive = t.k === active;
      const color = isActive ? '#FF6B1A' : '#86868b';
      return (
        <button key={t.k} onClick={() => onChange(t.k)} style={{
          background: 'transparent', border: 0, cursor: 'pointer',
          color, padding: '8px 4px',
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
          transition: 'color 180ms',
        }}>
          {t.icon(color)}
          <span style={{ fontSize: 10, fontWeight: isActive ? 600 : 500, letterSpacing: '-0.005em' }}>{t.label}</span>
        </button>
      );
    })}
  </nav>
);

// ---- APP SHELL (native — no fake phone chrome) ----
// Centred 460-wide card with a subtle bevel on wide viewports so it doesn't
// look marooned in black. Edge-to-edge on phones.
const IOSFrame = ({ children }) => (
  <div style={{
    width: '100%', maxWidth: 460, minHeight: '100dvh',
    background: '#0a0a0a',
    position: 'relative',
    margin: '0 auto',
    boxShadow: '0 0 0 1px rgba(255,255,255,0.04), 0 60px 120px rgba(0,0,0,0.55)',
  }}>
    {children}
  </div>
);

// Back-to-site topbar — constant across all tabs. Collapses labels to icons
// at ultra-narrow widths (<=380) so iPhone SE / folded phones still fit.
const TopBar = () => (
  <div style={{
    position: 'sticky', top: 0, zIndex: 20,
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    padding: '10px 14px',
    background: 'rgba(10,10,10,0.72)',
    backdropFilter: 'saturate(180%) blur(14px)',
    WebkitBackdropFilter: 'saturate(180%) blur(14px)',
    borderBottom: '1px solid rgba(255,255,255,0.06)',
  }}>
    <a href="../marketing/" aria-label="Back to site" title="Back to site"
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '6px 10px 6px 8px', borderRadius: 8,
        background: 'rgba(255,255,255,0.04)',
        color: '#ddd', fontSize: 13, textDecoration: 'none',
        letterSpacing: '-0.011em',
        transition: 'background 160ms',
      }}
      onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.08)'}
      onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,0.04)'}
    >
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
      <span className="topbar-label">Back to site</span>
    </a>
    <a href="/sign-out" aria-label="Sign out" title="Sign out"
      onClick={(e) => {
        e.preventDefault();
        if (confirm('Sign out of the admin?')) window.location.href = '/sign-in';
      }}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '6px 10px', borderRadius: 8,
        background: 'transparent', color: '#86868b',
        fontSize: 12, letterSpacing: '0.08em', textTransform: 'uppercase',
        textDecoration: 'none',
        transition: 'color 160ms',
      }}
      onMouseEnter={e => e.currentTarget.style.color = '#fff'}
      onMouseLeave={e => e.currentTarget.style.color = '#86868b'}
    >
      <svg width="14" height="14" 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-2h4M16 17l5-5-5-5M21 12H9"/></svg>
      <span className="topbar-label">Sign out</span>
    </a>
  </div>
);

// Live "Last synced · Xs ago" strip. Updates every second; flips to pulsing
// orange dot when mocked "new activity" arrives.
const LastSynced = () => {
  const [since, setSince] = useStateS(0);
  useEffectS(() => {
    const id = setInterval(() => setSince(s => s + 1), 1000);
    return () => clearInterval(id);
  }, []);
  const label = since < 10 ? `${since}s ago` : since < 60 ? `${since}s ago` : `${Math.floor(since / 60)} min ago`;
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      marginTop: 8, fontSize: 11, color: '#86868b',
      fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.04em',
    }}>
      <span style={{
        width: 6, height: 6, borderRadius: '50%', background: '#30d158',
        boxShadow: '0 0 8px rgba(48,209,88,0.6)',
        animation: 'pulseDot 2.4s ease-in-out infinite',
      }} />
      <span style={{ textTransform: 'uppercase' }}>Last synced · {label}</span>
    </div>
  );
};

// ---- SHELL ----
const AdminShell = () => {
  const [tab, setTab] = useStateS(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get('tab') || localStorage.getItem('admin.tab') || 'bookings';
  });
  useEffectS(() => { localStorage.setItem('admin.tab', tab); }, [tab]);

  const TITLES = {
    leads:    { title: 'Leads',    subtitle: `${LEADS.length} new enquir${LEADS.length === 1 ? 'y' : 'ies'}` },
    bookings: { title: 'Bookings', subtitle: `${BOOKINGS.length} in the shop` },
    shop:     { title: 'Shop',     subtitle: 'Services & stock' },
    settings: { title: 'Settings', subtitle: 'The Fone Shop' },
  };
  const t = TITLES[tab];

  return (
    <IOSFrame>
      <div style={{
        position: 'absolute', inset: 0,
        paddingBottom: 90,
        overflowY: 'auto', overflowX: 'hidden',
      }}>
        <TopBar />
        {/* Header */}
        <header style={{ padding: '12px 20px 14px' }}>
          <div className="eyebrow-full"><Eyebrow tone="ember">THE FONE SHOP · ADMIN</Eyebrow></div>
          <span className="eyebrow-logo" aria-label="The Fone Shop">
            <img src="../../assets/the-fone-shop-logo-mark.png" alt="The Fone Shop" style={{ height: 40, width: 'auto', display: 'block', marginLeft: -8, marginBottom: 4 }} />
          </span>
          <h1 style={{ margin: '6px 0 2px', fontSize: 32, fontWeight: 600, letterSpacing: '-0.03em', lineHeight: 1.05 }}>{t.title}</h1>
          <div style={{ fontSize: 13, color: '#86868b' }}>{t.subtitle}</div>
          <LastSynced />
        </header>
        <main style={{ padding: '6px 20px 24px' }}>
          {tab === 'leads' && <LeadsTab onConvert={() => setTab('bookings')} />}
          {tab === 'bookings' && <BookingsTab />}
          {tab === 'shop' && <ShopTab />}
          {tab === 'settings' && <SettingsTab />}
        </main>
      </div>
      <TabBar active={tab} onChange={setTab} />
    </IOSFrame>
  );
};

Object.assign(window, { SettingsTab, TabBar, IOSFrame, AdminShell });
