/* redesign-primitives.jsx — Shared UI atoms for the redesign */
/* global React, Icon */
const { useState, useEffect, useRef } = React;

// ─────────────────────────────────────────────────────────
// RDSidebar — slim sidebar for the artboard
// ─────────────────────────────────────────────────────────
function RDSidebar({ active = 'discover' }) {
  const items = [
    { id: 'dash',     label: 'Dashboard',  icon: Icon.home },
    { id: 'briefs',   label: 'Briefs',     icon: Icon.file, badge: 4 },
    { id: 'discover', label: 'Discover',   icon: Icon.search },
    { id: 'campaign', label: 'Campaigns',  icon: Icon.megaphone },
    { id: 'report',   label: 'Reports',    icon: Icon.chart },
  ];
  return (
    <div className="rd-side">
      <div className="logo">
        <div className="dot">P</div>
        <span>Prime</span>
      </div>
      <div className="nav-label">Workspace · Brand</div>
      {items.map((it) => (
        <div key={it.id} className={'nav-item' + (active === it.id ? ' active' : '')}>
          <span className="nav-icon">{it.icon}</span>
          <span>{it.label}</span>
          {it.badge ? <span className="nav-badge">{it.badge}</span> : null}
        </div>
      ))}
      <div className="nav-label">Library</div>
      <div className="nav-item">
        <span className="nav-icon">{Icon.users}</span>
        <span>Roster</span>
      </div>
      <div className="nav-item">
        <span className="nav-icon">{Icon.bag}</span>
        <span>Saved segments</span>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// RDTopbar
// ─────────────────────────────────────────────────────────
function RDTopbar() {
  return (
    <div className="rd-topbar">
      <div className="crumb"><span>Brand</span> · <span>Find</span> · <b>Discover</b></div>
      <div className="grow"></div>
      <div className="icon-btn">{Icon.bell}</div>
      <div className="icon-btn">{Icon.settings}</div>
      <div className="avatar">AT</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// RDPageHead — title + secondary count
// ─────────────────────────────────────────────────────────
function RDPageHead({ count }) {
  return (
    <div className="rd-page-head">
      <div>
        <h1>Discover creators.</h1>
        <div className="sub">
          <b>{count.toLocaleString()}</b> creators on TikTok, Instagram, YouTube · Shopee &amp; TikTok Shop · <b>Provenance-checked</b>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 8 }}>
        <button className="btn btn-ghost btn-sm">{Icon.sliders} Advanced filters</button>
        <button className="btn btn-primary btn-sm">{Icon.plus} Save segment</button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// RDNaturalSearch — natural-language brief input (hero)
// ─────────────────────────────────────────────────────────
function RDNaturalSearch({ active = true }) {
  // Visual representation: a parsed phrase with colored tokens + a caret.
  // Simulates "Brand types intent → AI extracts tokens"
  return (
    <div className={'rd-nl' + (active ? ' focus' : '')}>
      <div className="row1">
        <div className="spark-ai">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="m12 3 1.9 5.8a2 2 0 0 0 1.3 1.3L21 12l-5.8 1.9a2 2 0 0 0-1.3 1.3L12 21l-1.9-5.8a2 2 0 0 0-1.3-1.3L3 12l5.8-1.9a2 2 0 0 0 1.3-1.3Z" />
          </svg>
        </div>
        <div className="nl-input">
          <span className="typed">Find</span>
          <span className="nl-token cat">micro skincare creators</span>
          <span className="typed">in</span>
          <span className="nl-token geo">HCM</span>
          <span className="typed">under</span>
          <span className="nl-token budget">$5K · per post</span>
          <span className="typed">with</span>
          <span className="nl-token">ER ≥ 4%</span>
          <span className="typed">·</span>
          <span className="nl-token guard">bot &lt; 10%</span>
          <span className="caret"></span>
        </div>
        <button className="submit">
          Run brief {Icon.arrow}
        </button>
      </div>
      <div className="row2">
        <span className="lbl">Try:</span>
        <span className="suggest">"Mid-tier wellness creators ready to ship to HN in May"</span>
        <span className="suggest">"Re-book my top 3 from Q1 skincare push"</span>
        <span className="suggest">"Nano on TikTok Shop with derm authority"</span>
      </div>
      <div className="meta">
        <span className="dot"></span>
        <span><b>AI parsed</b> 5 tokens · <b>312</b> matches · <b>8</b> shortlisted by ROI per dollar</span>
        <span style={{ marginLeft: 'auto' }}>Filters update live below ↓</span>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// RDFilterBar — filter chips with guard variant
// ─────────────────────────────────────────────────────────
function RDFilterBar({ filters, onToggle, density = 'comfy' }) {
  return (
    <div className="rd-filters" style={{ marginTop: density === 'compact' ? 10 : 14, marginBottom: density === 'compact' ? 12 : 16 }}>
      <span className="cap-label" style={{ marginRight: 4 }}>Filters</span>
      {filters.map((c) => (
        <button key={c.id}
          className={'chip' + (c.active ? ' active' : '') + (c.guard ? ' guard' : '')}
          onClick={() => onToggle && onToggle(c.id)}
        >
          {c.guard && (
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
            </svg>
          )}
          {c.label}
          <span className="cnt">{c.count}</span>
        </button>
      ))}
      <button className="more">+3 more</button>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// ProvenanceBadge — micro source + freshness chip
// ─────────────────────────────────────────────────────────
function ProvenanceBadge({ src = 'api', age = '2d', extraClass = '' }) {
  const labelMap = { api: 'API', crawl: 'CRL', import: 'IMP' };
  const cls = age && /^(d|w|mo|m)/.test(age.replace(/[0-9]/g, '')) && /^[0-9]+(?:d|w|mo)$/.test(age)
    ? (parseInt(age, 10) > 14 ? 'stale' : 'fresh')
    : (age && age.endsWith('h')) ? 'fresh' : '';
  return (
    <span className={'prov ' + (extraClass || cls)}>
      <span className={'src ' + src}>{labelMap[src] || 'API'}</span>
      <span className="age">{age} ago</span>
    </span>
  );
}

// ─────────────────────────────────────────────────────────
// RiskBadge — color-coded dot + label
// ─────────────────────────────────────────────────────────
function RiskBadge({ bot, growth }) {
  const cls = bot >= 15 ? 'bad' : bot >= 10 ? 'warn' : 'ok';
  const lbl = bot >= 15 ? `Bot ${bot}% · check` : bot >= 10 ? `Bot ${bot}%` : `Bot ${bot}% · ok`;
  return (
    <span className={'risk ' + cls}>
      <span className="dot"></span>
      {lbl}
    </span>
  );
}

// ─────────────────────────────────────────────────────────
// RebookChip
// ─────────────────────────────────────────────────────────
function RebookChip({ count, last }) {
  if (!count) return null;
  return (
    <span className="rebook">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M21 3v5h-5"/>
        <path d="M21 12a9 9 0 0 1-15 6.7L3 16"/><path d="M3 21v-5h5"/>
      </svg>
      <span className="x">{count}×</span>
      <span>since {last}</span>
    </span>
  );
}

// ─────────────────────────────────────────────────────────
// CPEBadge — cost per engagement
// ─────────────────────────────────────────────────────────
function CPEBadge({ value }) {
  return (
    <div className="cpe">
      <div className="lbl">$ / engage</div>
      <div className="val">${value.toFixed(2)}<span className="sub">est</span></div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// MatchChip — horizontal score chip (replaces full circle in cards)
// ─────────────────────────────────────────────────────────
function MatchChip({ score }) {
  const cls = score >= 80 ? '' : score >= 65 ? 'warn' : 'bad';
  return (
    <div className={'match-chip ' + cls} style={{ '--w': score + '%' }}>
      <div className="fill" style={{ width: score + '%' }}></div>
      <div className="v">{score}<span className="pct">%</span></div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// Tiny inline platform icon helper
// ─────────────────────────────────────────────────────────
function PlatformIcon({ name }) {
  const map = { tiktok: Icon.tiktok, instagram: Icon.instagram, youtube: Icon.youtube };
  return <span style={{ color: 'var(--ink-soft)' }}>{map[name]}</span>;
}

// Compact follower formatter (482K, 1.2M)
function fmtK(n) {
  if (n >= 1_000_000) return (n / 1_000_000).toFixed(1).replace(/\.0$/, '') + 'M';
  if (n >= 1000) return Math.round(n / 1000) + 'K';
  return String(n);
}

Object.assign(window, {
  RDSidebar, RDTopbar, RDPageHead, RDNaturalSearch, RDFilterBar,
  ProvenanceBadge, RiskBadge, RebookChip, CPEBadge, MatchChip,
  PlatformIcon, fmtK
});
