/* Accounts tab — refined */

function AccountsTab() {
  const [filter, setFilter] = useState('all');
  const [selected, setSelected] = useState({ mk: 'de', ch: 'ig' });

  const grid = [];
  MARKETS.forEach(m => {
    ['ig','tt'].forEach(ch => {
      let status = 'disconnected';
      if (m.code === 'de') status = 'connected';
      else if (m.code === 'uk' && ch === 'tt') status = 'connected';
      else if (m.code === 'uk' && ch === 'ig') status = 'expired';
      grid.push({ mk: m.code, ch, status });
    });
  });

  const visible = grid.filter(g =>
    filter === 'all' ? true :
    filter === 'connected' ? g.status === 'connected' :
    filter === 'expired' ? g.status === 'expired' :
    g.status === 'disconnected'
  );

  return (
    <div style={{ padding: '24px 36px 60px', display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div className="anim-fade-up" style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
        <div style={{
          display: 'inline-flex', alignItems: 'baseline', gap: 8,
          padding: '8px 14px', borderRadius: 10, background: 'var(--bg-1)', border: '1px solid var(--line)',
        }}>
          <span className="display" style={{ fontSize: 22 }}><Counter to={3} /></span>
          <span className="caps" style={{ color: 'var(--fg-3)' }}>/ 12 connected</span>
        </div>

        <div className="seg">
          <button className={filter==='all'?'on':''} onClick={()=>setFilter('all')}>All · 12</button>
          <button className={filter==='connected'?'on':''} onClick={()=>setFilter('connected')}>Connected · 3</button>
          <button className={filter==='disconnected'?'on':''} onClick={()=>setFilter('disconnected')}>Not connected · 8</button>
          <button className={filter==='expired'?'on':''} onClick={()=>setFilter('expired')}>Expired · 1</button>
        </div>

        <div style={{ flex: 1 }} />
        <button className="btn press"><Icon name="refresh" size={16} /> Refresh tokens</button>
        <button className="btn primary press"><Icon name="link" size={16} /> Connect all</button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 18 }}>
        <div className="stagger" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 12, alignContent: 'start' }}>
          {visible.map((a, i) => (
            <AccountCard key={i} a={a} active={selected.mk === a.mk && selected.ch === a.ch} onClick={() => setSelected(a)} />
          ))}
        </div>

        <DetailPanel a={selected} />
      </div>
    </div>
  );
}

function AccountCard({ a, active, onClick }) {
  const status = a.status;
  const market = MARKETS.find(m => m.code === a.mk);
  return (
    <button onClick={onClick} className="press lift" style={{
      padding: 16, borderRadius: 14, textAlign: 'left',
      background: active ? 'var(--bg-2)' : 'var(--bg-1)',
      border: '1px solid ' + (active ? 'var(--line-3)' : 'var(--line)'),
      display: 'flex', flexDirection: 'column', gap: 12,
      cursor: 'pointer', color: 'var(--fg)',
      boxShadow: active ? '0 0 0 4px rgba(122,167,255,.08)' : 'none',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{
            width: 38, height: 38, borderRadius: 99,
            background: 'var(--bg-3)', border: '1px solid var(--line-2)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 20,
          }}><Flag code={a.mk} size={20} /></div>
          <div>
            <div style={{ fontFamily: 'Hanken Grotesk', fontSize: 16, fontWeight: 600 }}>{a.mk.toUpperCase()}</div>
            <div className="mono" style={{ fontSize: 10.5, color: 'var(--fg-3)' }}>{a.ch === 'ig' ? 'Instagram' : 'TikTok'}</div>
          </div>
        </div>
        <StatusPill status={status} />
      </div>
      <div className="hairline" style={{
        background: status === 'expired' ? 'rgba(241,192,84,.06)' : 'var(--bg-2)',
        borderColor: status === 'expired' ? 'rgba(241,192,84,.2)' : 'var(--line)',
        borderRadius: 10, padding: 10, display: 'flex', flexDirection: 'column', gap: 3,
      }}>
        {status === 'connected' && <>
          <span className="caps" style={{ color: 'var(--fg-3)' }}>Account</span>
          <span className="mono" style={{ fontSize: 12 }}>@hookline.{a.mk}</span>
          <span style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{market.name} · Business</span>
        </>}
        {status === 'expired' && <>
          <span className="caps" style={{ color: 'var(--warn)' }}>Action required</span>
          <span style={{ fontSize: 12 }}>Token expired 2 days ago · paused.</span>
        </>}
        {status === 'disconnected' && <>
          <span className="caps" style={{ color: 'var(--fg-3)' }}>Setup needed</span>
          <span style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{market.name} not connected yet.</span>
        </>}
      </div>
      <button className="btn sm press" style={{
        justifyContent: 'center',
        background: status === 'expired' ? 'var(--warn)' : status === 'disconnected' ? 'var(--fg)' : 'var(--bg-2)',
        color: status === 'expired' ? '#2a1f0a' : status === 'disconnected' ? '#0e0e10' : 'var(--fg)',
        borderColor: status === 'connected' ? 'var(--line)' : 'transparent',
      }}>
        {status === 'connected' && 'Manage'}
        {status === 'expired' && 'Reauthorize now'}
        {status === 'disconnected' && 'Connect'}
      </button>
    </button>
  );
}

function StatusPill({ status }) {
  const map = {
    connected:    { label: 'Connected',     color: 'var(--good)' },
    expired:      { label: 'Token expired', color: 'var(--warn)' },
    disconnected: { label: 'Not connected', color: 'var(--fg-3)' },
  };
  const c = map[status];
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontFamily: 'JetBrains Mono', fontSize: 10, letterSpacing: 0.06, textTransform: 'uppercase', color: c.color }}>
      <span style={{ width: 6, height: 6, borderRadius: 99, background: c.color }} />
      {c.label}
    </span>
  );
}

function DetailPanel({ a }) {
  const market = MARKETS.find(m => m.code === a.mk);
  return (
    <aside className="panel anim-fade-up" style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 14, height: 'fit-content' }}>
      <div className="display" style={{ fontSize: 22 }}>{a.mk.toUpperCase()} · {a.ch === 'ig' ? 'Instagram' : 'TikTok'}</div>
      <div className="mono" style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{market?.name} · @hookline.{a.mk}</div>

      <div className="hairline" style={{ borderRadius: 10, padding: 12, display: 'flex', flexDirection: 'column', gap: 8, background: 'var(--bg-2)' }}>
        <Row k="Provider" v="Meta Graph API" />
        <Row k="Connected" v="2026-04-12 14:23" />
        <Row k="Token expires" v="2026-06-11 (32 days)" />
        <Row k="Last refresh" v="2 hours ago" last />
      </div>

      <div className="caps" style={{ color: 'var(--fg-3)' }}>Granted scopes</div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
        <span className="chip">instagram_business_basic</span>
        <span className="chip">instagram_business_content_publish</span>
        <span className="chip">pages_show_list</span>
      </div>

      <button className="btn primary press" style={{ justifyContent: 'center' }}>
        <Icon name="refresh" size={16} /> Reauthorize
      </button>
      <button className="btn press" style={{ justifyContent: 'center' }}>
        <Icon name="science" size={16} /> Send test post
      </button>
      <button className="btn ghost press" style={{ justifyContent: 'center', color: 'var(--bad)' }}>
        <Icon name="link_off" size={16} /> Disconnect
      </button>
    </aside>
  );
}

function Row({ k, v, last }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      paddingBottom: last ? 0 : 8, borderBottom: last ? 'none' : '1px solid var(--line)',
      paddingTop: 0,
    }}>
      <span className="mono" style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{k}</span>
      <span className="mono" style={{ fontSize: 11.5 }}>{v}</span>
    </div>
  );
}

Object.assign(window, { AccountsTab });
