/* screen-brand-misc.jsx — Import + Settings */
/* global React, AppSidebar, AppTopbar, useRouter, useT, Counter, Sparkline, Avatar, Pill, Icon, useInView */

// ── Import (CSV) ──────────────────────────────────────────────────
function ScreenBrandImport() {
  const { t } = useT();
  const [step, setStep] = React.useState('upload'); // upload | mapping | processing | done
  const [progress, setProgress] = React.useState(0);

  const handleUpload = () => {
    setStep('mapping');
  };
  const handleProcess = () => {
    setStep('processing');
    let p = 0;
    const iv = setInterval(() => {
      p += 4;
      setProgress(p);
      if (p >= 100) {
        clearInterval(iv);
        setTimeout(() => setStep('done'), 200);
      }
    }, 60);
  };

  return (
    <div className="app-shell">
      <AppSidebar portal="brand" active="brand-import" />
      <main className="main">
        <AppTopbar />
        <div className="row items-end justify-between mb-6">
          <div>
            <span className="pill pill-yellow">Data ingestion</span>
            <h1 className="page-title" style={{ marginTop: 8 }}>{t('brand.import.title')}</h1>
            <div className="page-subtitle">{t('brand.import.subtitle')}</div>
          </div>
          <button className="btn btn-ghost btn-sm">{Icon.external} Download template</button>
        </div>

        {/* Stepper */}
        <div className="row items-center mb-6" style={{ maxWidth: 600 }}>
          {[
            { id: 'upload', l: 'Upload CSV', icon: Icon.file },
            { id: 'mapping', l: 'Map columns', icon: Icon.sliders },
            { id: 'processing', l: 'Process', icon: Icon.spark },
            { id: 'done', l: 'Done', icon: Icon.check },
          ].map((s, i, all) => {
            const order = all.findIndex(x => x.id === step);
            const passed = i < order;
            const active = i === order;
            return (
              <React.Fragment key={s.id}>
                <div className="row items-center gap-8">
                  <div style={{
                    width: 32, height: 32, borderRadius: 999,
                    background: passed ? 'var(--mint)' : active ? 'var(--ink)' : 'var(--bg-soft)',
                    color: passed ? 'var(--ink)' : active ? 'white' : 'var(--ink-soft)',
                    display: 'grid', placeItems: 'center', transition: 'all .3s'
                  }}>{passed ? Icon.check : s.icon}</div>
                  <span className="bold" style={{ fontSize: 13, color: active ? 'var(--ink)' : 'var(--ink-soft)' }}>{s.l}</span>
                </div>
                {i < all.length - 1 && (
                  <div style={{ flex: 1, height: 2, margin: '0 14px', background: passed ? 'var(--mint)' : 'var(--bg-soft)', borderRadius: 999, transition: 'background .3s' }} />
                )}
              </React.Fragment>
            );
          })}
        </div>

        {step === 'upload' && <UploadDropzone onUpload={handleUpload} />}
        {step === 'mapping' && <ColumnMapping onContinue={handleProcess} />}
        {step === 'processing' && <ProcessingView progress={progress} />}
        {step === 'done' && <ImportDone />}

        {/* Recent imports */}
        <div className="mt-6">
          <div className="cap-label mb-2">Recent imports</div>
          <div className="card-elevated" style={{ padding: 0, overflow: 'hidden' }}>
            <table className="tbl">
              <thead>
                <tr>
                  <th>File</th>
                  <th>Rows</th>
                  <th>Status</th>
                  <th>Source</th>
                  <th>When</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {[
                  ['tiktok_kols_may.csv', '412 rows', 'success', 'TikTok manual', '2h ago'],
                  ['ig_creators_q2.csv', '184 rows', 'success', 'Instagram', '1d ago'],
                  ['shopee_sellers.csv', '96 rows', 'partial', 'Shopee', '3d ago'],
                  ['old_export.csv', '32 rows', 'failed', 'Manual', '1w ago'],
                ].map(([f, r, s, src, w], i) => (
                  <tr key={i}>
                    <td><div className="bold">{f}</div></td>
                    <td className="tabular">{r}</td>
                    <td>{<Pill variant={s === 'success' ? 'mint' : s === 'partial' ? 'yellow' : 'pink'}>{s}</Pill>}</td>
                    <td className="muted" style={{ fontSize: 12 }}>{src}</td>
                    <td className="muted" style={{ fontSize: 12 }}>{w}</td>
                    <td className="text-right"><button className="btn-sm" style={{ background: 'transparent', border: 0, color: 'var(--ink-soft)', cursor: 'pointer' }}>{Icon.external}</button></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </main>
    </div>
  );
}

function UploadDropzone({ onUpload }) {
  const [drag, setDrag] = React.useState(false);
  return (
    <div className="card-elevated" style={{ padding: 0 }}>
      <div
        onDragOver={(e) => { e.preventDefault(); setDrag(true); }}
        onDragLeave={() => setDrag(false)}
        onDrop={(e) => { e.preventDefault(); setDrag(false); onUpload(); }}
        onClick={onUpload}
        style={{
          margin: 24,
          padding: '60px 40px',
          border: '2.5px dashed ' + (drag ? 'var(--cyan)' : 'var(--line)'),
          background: drag ? 'rgba(0,156,255,0.06)' : 'var(--bg-soft)',
          borderRadius: 18,
          textAlign: 'center',
          cursor: 'pointer',
          transition: 'all .2s'
        }}>
        <div style={{
          width: 72, height: 72, borderRadius: 999,
          background: 'linear-gradient(135deg, #009CFF, #1C1CC9)',
          color: 'white', display: 'grid', placeItems: 'center',
          margin: '0 auto 20px',
          fontSize: 32,
          animation: drag ? 'bounce 0.6s ease-in-out infinite' : 'none',
          boxShadow: '0 12px 30px rgba(28,28,201,0.32)'
        }}>↑</div>
        <div className="font-display bold" style={{ fontSize: 22, letterSpacing: '-0.02em' }}>Drop your CSV here</div>
        <div className="muted" style={{ fontSize: 14, marginTop: 6 }}>or click to browse · max 50MB · UTF-8 encoded</div>

        <div className="row items-center justify-center gap-12 mt-4" style={{ marginTop: 20 }}>
          {['.csv', '.xlsx', '.tsv'].map(f => (
            <Pill key={f} variant="ink">{f}</Pill>
          ))}
        </div>
      </div>
      <div style={{ padding: '0 24px 24px' }}>
        <div className="cap-label mb-2">Required columns</div>
        <div className="row gap-6" style={{ flexWrap: 'wrap' }}>
          {['handle', 'platform', 'followers', 'engagement_rate', 'category', 'country'].map(c => (
            <Pill key={c} variant="lav">{c}</Pill>
          ))}
        </div>
      </div>
      <style>{`@keyframes bounce { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-10px); } }`}</style>
    </div>
  );
}

function ColumnMapping({ onContinue }) {
  const rows = [
    ['Column A: handle', 'handle', 'matched', '@linhchau, @maivy, @hagiang'],
    ['Column B: name', 'name', 'matched', 'Linh Châu, Mai Vy, Hà Giang'],
    ['Column C: platform', 'platform', 'matched', 'tiktok, instagram, tiktok'],
    ['Column D: count', 'followers', 'inferred', '482000, 1200000, 320000'],
    ['Column E: er_pct', 'engagement_rate', 'inferred', '6.2, 5.8, 7.1'],
    ['Column F: niche', 'category', 'matched', 'skincare, lifestyle, beauty'],
    ['Column G: location', 'country', 'matched', 'VN, VN, VN'],
    ['Column H: phone', '— skip —', 'skipped', '0901..., 0908...'],
  ];
  return (
    <div className="card-elevated" style={{ padding: 24 }}>
      <div className="row items-center justify-between mb-3">
        <div>
          <div className="title-md">Confirm column mapping</div>
          <div className="muted" style={{ fontSize: 13 }}>tiktok_kols_may.csv · 412 rows · AI auto-mapped 7 of 8 columns</div>
        </div>
        <Pill variant="mint" icon={Icon.spark}>AI mapped</Pill>
      </div>
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <table className="tbl">
          <thead>
            <tr>
              <th>Source column</th>
              <th>Maps to</th>
              <th>Confidence</th>
              <th>Sample data</th>
            </tr>
          </thead>
          <tbody>
            {rows.map(([src, dst, conf, sample], i) => (
              <tr key={i}>
                <td className="bold">{src}</td>
                <td>
                  <select className="input" style={{ padding: '6px 10px', fontSize: 12, width: 'auto' }}>
                    <option>{dst}</option>
                  </select>
                </td>
                <td>{<Pill variant={conf === 'matched' ? 'mint' : conf === 'inferred' ? 'yellow' : 'pink'}>{conf}</Pill>}</td>
                <td className="muted" style={{ fontSize: 11 }}>{sample}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="row justify-between mt-6">
        <button className="btn btn-ghost">← Back</button>
        <button className="btn btn-primary" onClick={onContinue}>{Icon.spark} Process 412 rows</button>
      </div>
    </div>
  );
}

function ProcessingView({ progress }) {
  return (
    <div className="card-elevated" style={{ padding: 48, textAlign: 'center', position: 'relative', overflow: 'hidden' }}>
      <div className="orb" style={{ width: 100, height: 100, margin: '0 auto' }} />
      <div className="font-display bold mt-6" style={{ fontSize: 28, letterSpacing: '-0.025em' }}>Processing your data…</div>
      <div className="muted mb-6" style={{ fontSize: 14, marginTop: 6 }}>
        Validating rows, enriching with our crawler, computing tier &amp; levels.
      </div>
      <div style={{ maxWidth: 480, margin: '0 auto' }}>
        <div style={{ height: 12, background: 'var(--bg-soft)', borderRadius: 999, overflow: 'hidden' }}>
          <div style={{
            height: '100%', width: progress + '%',
            background: 'linear-gradient(90deg, var(--cyan), var(--indigo))', borderRadius: 999, transition: 'width .1s'
          }} />
        </div>
        <div className="row items-center justify-between mt-2" style={{ fontSize: 12 }}>
          <span className="font-display bold tabular" style={{ fontSize: 14 }}>{progress}%</span>
          <span className="muted">{Math.round(412 * progress / 100)} / 412 rows</span>
        </div>
      </div>
      <div className="row items-center justify-center gap-8 mt-6">
        <div className="ai-thinking"><span className="dot" /><span className="dot" /><span className="dot" /></div>
        <span className="muted" style={{ fontSize: 13 }}>AI validating data quality…</span>
      </div>
    </div>
  );
}

function ImportDone() {
  return (
    <div className="card-elevated" style={{ padding: 36 }}>
      <div className="row items-center gap-16">
        <div style={{
          width: 72, height: 72, borderRadius: 999,
          background: 'var(--mint)', color: 'var(--ink)',
          display: 'grid', placeItems: 'center', fontSize: 32, fontWeight: 800
        }}>{Icon.check}</div>
        <div className="flex-1">
          <div className="font-display bold" style={{ fontSize: 28, letterSpacing: '-0.025em' }}>
            <Counter to={412} /> rows imported successfully
          </div>
          <div className="muted" style={{ fontSize: 14, marginTop: 4 }}>tiktok_kols_may.csv · 6 duplicates merged · 0 errors</div>
        </div>
        <div className="row gap-8">
          <button className="btn btn-ghost">Import another</button>
          <button className="btn btn-primary">{Icon.search} Go to Discover</button>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginTop: 24 }}>
        {[
          ['New creators', 384, 'var(--cyan)'],
          ['Updated', 22, 'var(--mint-deep)'],
          ['Duplicates merged', 6, 'var(--yellow-deep)'],
          ['Errors', 0, 'var(--coral)'],
        ].map(([l, v, c], i) => (
          <div key={i} style={{ padding: 18, background: 'var(--bg-soft)', borderRadius: 12 }}>
            <div className="cap-label">{l}</div>
            <div className="font-display bold tabular" style={{ fontSize: 32, color: c, marginTop: 4 }}>
              <Counter to={v} duration={1500} />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Settings (Org / Team / Billing / Notifications) ──────────────────────
function ScreenBrandSettings() {
  const { t } = useT();
  const [tab, setTab] = React.useState('org');
  const tabs = [
    { id: 'org', l: 'Organization' },
    { id: 'team', l: 'Team' },
    { id: 'billing', l: 'Billing' },
    { id: 'notifications', l: 'Notifications' },
    { id: 'api', l: 'API & integrations' },
  ];
  return (
    <div className="app-shell">
      <AppSidebar portal="brand" active="brand-settings" />
      <main className="main">
        <AppTopbar />
        <h1 className="page-title">{t('brand.settings.title')}</h1>
        <div className="page-subtitle">Workspace, team and billing configuration.</div>

        <div className="row gap-4 mt-6" style={{ borderBottom: '1px solid var(--line)' }}>
          {tabs.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              background: 'transparent', border: 0, padding: '12px 14px', fontSize: 13, fontWeight: 700, fontFamily: 'inherit',
              color: tab === t.id ? 'var(--ink)' : 'var(--ink-soft)',
              borderBottom: '2px solid ' + (tab === t.id ? 'var(--ink)' : 'transparent'),
              marginBottom: -1, cursor: 'pointer'
            }}>{t.l}</button>
          ))}
        </div>

        <div className="mt-6">
          {tab === 'org' && <OrgSettings />}
          {tab === 'team' && <TeamSettings />}
          {tab === 'billing' && <BillingSettings />}
          {tab === 'notifications' && <NotifSettings />}
          {tab === 'api' && <ApiSettings />}
        </div>
      </main>
    </div>
  );
}

function OrgSettings() {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
      <div className="card-elevated">
        <div className="title-md mb-3">Organization profile</div>
        <div className="row items-center gap-16 mb-4">
          <div style={{
            width: 80, height: 80, borderRadius: 16,
            background: 'linear-gradient(135deg, var(--cyan), var(--indigo))',
            color: 'white', display: 'grid', placeItems: 'center',
            fontFamily: 'Space Grotesk', fontWeight: 800, fontSize: 32
          }}>C</div>
          <div className="flex-1">
            <div className="bold">Coolmate VN</div>
            <div className="muted" style={{ fontSize: 12 }}>coolmate-vn · Brand · created Mar 2024</div>
            <button className="btn btn-ghost btn-sm mt-2">Upload logo</button>
          </div>
        </div>
        <div>
          <label className="label">Organization name</label>
          <input className="input" defaultValue="Coolmate VN" />
        </div>
        <div className="mt-4">
          <label className="label">Description</label>
          <textarea className="input" rows="3" defaultValue="Vietnamese DTC menswear brand. Active categories: apparel, accessories, lifestyle." style={{ resize: 'vertical', fontFamily: 'inherit' }} />
        </div>
        <div className="row gap-12 mt-4">
          <div className="flex-1">
            <label className="label">Industry</label>
            <select className="input">
              <option>DTC retail</option>
            </select>
          </div>
          <div className="flex-1">
            <label className="label">Country</label>
            <select className="input">
              <option>🇻🇳 Vietnam</option>
            </select>
          </div>
        </div>
        <div className="row gap-8 mt-6 justify-end">
          <button className="btn btn-ghost btn-sm">Cancel</button>
          <button className="btn btn-primary btn-sm">Save changes</button>
        </div>
      </div>

      <div>
        <div className="card-elevated">
          <div className="title-md mb-3">Workspace usage</div>
          {[
            ['Briefs created', 24, 100, 'var(--cyan)'],
            ['Active campaigns', 3, 10, 'var(--mint-deep)'],
            ['Influencers tracked', 412, 1000, 'var(--indigo)'],
            ['AI shortlists / mo', 36, 50, 'var(--pink-hot)'],
          ].map(([l, used, total, c], i) => (
            <div key={i} className="mb-3">
              <div className="row items-center justify-between mb-1">
                <span style={{ fontSize: 13, fontWeight: 600 }}>{l}</span>
                <span className="tabular bold" style={{ fontSize: 12 }}>{used} <span className="muted">/ {total}</span></span>
              </div>
              <div style={{ height: 6, background: 'var(--bg-soft)', borderRadius: 999, overflow: 'hidden' }}>
                <div style={{ height: '100%', width: ((used/total)*100) + '%', background: c, borderRadius: 999, transformOrigin: 'left',
                  animation: `grow-w 1s ${0.2 + i*0.1}s cubic-bezier(.4,0,.2,1) both`, transform: 'scaleX(0)' }} />
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function TeamSettings() {
  const members = [
    { n: 'Trang Lê', email: 'trang@coolmate.vn', role: 'Owner', last: 'now' },
    { n: 'Đức Anh', email: 'duc@coolmate.vn', role: 'Admin', last: '2h ago' },
    { n: 'Mai Linh', email: 'mai.linh@coolmate.vn', role: 'Editor', last: '1d ago' },
    { n: 'Hoàng Vũ', email: 'vu@coolmate.vn', role: 'Viewer', last: '4d ago' },
    { n: 'Bích Phương', email: 'phuong@coolmate.vn', role: 'Editor', last: '1w ago' },
  ];
  return (
    <div className="card-elevated" style={{ padding: 0, overflow: 'hidden' }}>
      <div className="row items-center justify-between" style={{ padding: 20, borderBottom: '1px solid var(--line)' }}>
        <div>
          <div className="title-md">Team members</div>
          <div className="muted" style={{ fontSize: 12 }}>{members.length} members · 1 invite pending</div>
        </div>
        <button className="btn btn-primary btn-sm">{Icon.plus} Invite member</button>
      </div>
      <table className="tbl">
        <thead>
          <tr>
            <th>Member</th>
            <th>Role</th>
            <th>Last active</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          {members.map((m, i) => (
            <tr key={i}>
              <td>
                <div className="row items-center gap-12">
                  <Avatar name={m.n} size={36} />
                  <div>
                    <div className="bold" style={{ fontSize: 13 }}>{m.n}</div>
                    <div className="muted" style={{ fontSize: 11 }}>{m.email}</div>
                  </div>
                </div>
              </td>
              <td><Pill variant={m.role === 'Owner' ? 'mint' : m.role === 'Admin' ? 'cyan' : m.role === 'Editor' ? 'lav' : 'ink'}>{m.role}</Pill></td>
              <td className="muted" style={{ fontSize: 12 }}>{m.last}</td>
              <td className="text-right"><button className="btn-sm" style={{ background: 'transparent', border: 0, color: 'var(--ink-soft)', cursor: 'pointer' }}>···</button></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function BillingSettings() {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 18 }}>
      <div>
        <div className="card-elevated" style={{ padding: 24, background: 'linear-gradient(135deg, #002B50, #1C1CC9)', color: 'white', position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', top: -50, right: -50, width: 200, height: 200, borderRadius: '50%', background: 'radial-gradient(circle, rgba(121,254,231,0.5), transparent 60%)', filter: 'blur(20px)' }} />
          <div style={{ position: 'relative', zIndex: 1 }}>
            <div className="row items-center gap-8">
              <Pill variant="dark"><span style={{ color: 'var(--mint)' }}>●</span> Active</Pill>
              <span style={{ fontSize: 12 }}>Renews June 13, 2026</span>
            </div>
            <div className="font-display" style={{ fontSize: 36, fontWeight: 700, marginTop: 14, letterSpacing: '-0.025em' }}>Growth plan</div>
            <div className="row items-end gap-6 mt-2">
              <span className="font-display tabular" style={{ fontSize: 48, fontWeight: 700 }}>$299</span>
              <span style={{ paddingBottom: 12, fontSize: 14, opacity: 0.7 }}>/ month</span>
            </div>
            <ul style={{ listStyle: 'none', padding: 0, margin: '20px 0 0', display: 'flex', flexDirection: 'column', gap: 8 }}>
              {['Unlimited briefs', '50 AI shortlists / month', '1,000 tracked KOLs', '10 team members', 'Priority support'].map(b => (
                <li key={b} className="row items-center gap-8" style={{ fontSize: 13 }}>
                  <span style={{ width: 18, height: 18, borderRadius: 999, background: 'var(--mint)', color: 'var(--ink)', display: 'grid', placeItems: 'center' }}>{Icon.check}</span>
                  {b}
                </li>
              ))}
            </ul>
            <div className="row gap-8 mt-6">
              <button className="btn btn-yellow btn-sm">Upgrade to Scale</button>
              <button className="btn btn-sm" style={{ background: 'rgba(255,255,255,0.12)', color: 'white', boxShadow: 'inset 0 0 0 1.5px rgba(255,255,255,0.3)' }}>Manage</button>
            </div>
          </div>
        </div>

        <div className="card-elevated mt-4">
          <div className="title-md mb-3">Recent invoices</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            {[
              ['Apr 13, 2026', 'INV-2604-001', '$299.00', 'paid'],
              ['Mar 13, 2026', 'INV-2603-001', '$299.00', 'paid'],
              ['Feb 13, 2026', 'INV-2602-001', '$299.00', 'paid'],
              ['Jan 13, 2026', 'INV-2601-001', '$299.00', 'paid'],
            ].map(([d, n, a, s], i) => (
              <div key={i} className="row items-center gap-12" style={{ padding: '12px 4px', borderTop: i ? '1px solid var(--line)' : 'none' }}>
                <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--bg-soft)', display: 'grid', placeItems: 'center', color: 'var(--ink-soft)' }}>{Icon.file}</div>
                <div className="flex-1">
                  <div className="bold" style={{ fontSize: 13 }}>{n}</div>
                  <div className="muted" style={{ fontSize: 11 }}>{d}</div>
                </div>
                <div className="font-display bold tabular" style={{ fontSize: 14 }}>{a}</div>
                <Pill variant="mint">{s}</Pill>
                <button className="btn-sm" style={{ background: 'transparent', border: 0, color: 'var(--ink-soft)', cursor: 'pointer' }}>{Icon.external}</button>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="card-elevated">
        <div className="title-md mb-3">Payment method</div>
        <div style={{
          padding: 18, borderRadius: 12,
          background: 'linear-gradient(135deg, #002B50, #1C1CC9)',
          color: 'white', minHeight: 140, position: 'relative', overflow: 'hidden'
        }}>
          <div className="cap-label" style={{ color: 'rgba(255,255,255,0.6)' }}>Visa · ending</div>
          <div className="font-display tabular mt-2" style={{ fontSize: 24, letterSpacing: '0.1em' }}>•••• 4242</div>
          <div className="row items-center justify-between" style={{ marginTop: 18 }}>
            <span style={{ fontSize: 11 }}>Expires 06 / 27</span>
            <span style={{ fontSize: 14, fontWeight: 800, letterSpacing: '-0.02em' }}>VISA</span>
          </div>
        </div>
        <button className="btn btn-ghost btn-sm mt-4" style={{ width: '100%' }}>Update payment method</button>
      </div>
    </div>
  );
}

function NotifSettings() {
  const groups = [
    { l: 'Brief lifecycle', items: [
      ['Shortlist ready', true, 'email + in-app'],
      ['Creator accepted brief', true, 'in-app'],
      ['Brief deadline approaching', true, 'email'],
    ]},
    { l: 'Campaign updates', items: [
      ['Campaign launched', true, 'email + in-app'],
      ['New post published', true, 'in-app'],
      ['Performance alert', false, 'email'],
      ['Daily digest', true, 'email'],
    ]},
    { l: 'Account', items: [
      ['New team invite accepted', true, 'in-app'],
      ['Billing notifications', true, 'email'],
      ['Product updates &amp; tips', false, 'email'],
    ]}
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {groups.map((g, gi) => (
        <div key={gi} className="card-elevated">
          <div className="title-md mb-3">{g.l}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            {g.items.map(([l, on, ch], i) => (
              <div key={i} className="row items-center gap-12" style={{ padding: '12px 4px', borderTop: i ? '1px solid var(--line)' : 'none' }}>
                <div className="flex-1">
                  <div className="bold" style={{ fontSize: 13 }}>{l}</div>
                  <div className="muted" style={{ fontSize: 11 }}>{ch}</div>
                </div>
                <Toggle on={on} />
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function Toggle({ on: initialOn = false }) {
  const [on, setOn] = React.useState(initialOn);
  return (
    <button onClick={() => setOn(o => !o)} style={{
      width: 44, height: 24, borderRadius: 999,
      background: on ? 'var(--mint-deep)' : 'var(--line)',
      border: 0, cursor: 'pointer', position: 'relative',
      transition: 'background .2s'
    }}>
      <div style={{
        position: 'absolute', top: 2, left: on ? 22 : 2,
        width: 20, height: 20, borderRadius: 999,
        background: 'white', boxShadow: '0 2px 6px rgba(0,43,80,0.2)',
        transition: 'left .2s'
      }} />
    </button>
  );
}

function ApiSettings() {
  return (
    <div className="card-elevated">
      <div className="title-md mb-3">API access &amp; integrations</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
        {[
          { l: 'TikTok official', s: 'connected', c: 'var(--ink)', icon: Icon.tiktok },
          { l: 'Instagram Graph', s: 'connected', c: 'var(--pink-hot)', icon: Icon.instagram },
          { l: 'YouTube Data API', s: 'connected', c: 'var(--coral)', icon: Icon.youtube },
          { l: 'Shopee Open API', s: 'connected', c: 'var(--yellow-deep)', icon: Icon.bag },
          { l: 'Slack', s: 'connect', c: 'var(--indigo)', icon: Icon.bell },
          { l: 'Zapier', s: 'connect', c: 'var(--lavender-deep)', icon: Icon.spark },
        ].map((p, i) => (
          <div key={i} style={{ padding: 18, background: 'var(--bg-soft)', borderRadius: 14 }}>
            <div className="row items-center gap-12 mb-2">
              <div style={{ width: 36, height: 36, borderRadius: 9, background: p.c, color: 'white', display: 'grid', placeItems: 'center' }}>{p.icon}</div>
              <div className="bold" style={{ fontSize: 13 }}>{p.l}</div>
            </div>
            <div className="row items-center justify-between mt-2">
              <Pill variant={p.s === 'connected' ? 'mint' : 'cyan'}>{p.s}</Pill>
              <button className="btn-sm" style={{ background: 'transparent', border: 0, color: 'var(--cyan-dark)', fontWeight: 700, fontSize: 12, cursor: 'pointer' }}>
                {p.s === 'connected' ? 'Manage' : 'Connect'} {Icon.arrow}
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ScreenBrandImport, ScreenBrandSettings });
