// 1Radar v3 — Brands (table with customisable columns)

const fmtB = (n) => {
  if (n == null) return '—';
  if (n >= 1_000_000) return (n / 1_000_000).toFixed(1).replace(/\.0$/, '') + 'M';
  if (n >= 1_000)     return (n / 1_000).toFixed(1).replace(/\.0$/, '') + 'K';
  return n.toLocaleString();
};

// ── Column definitions ────────────────────────────────────────────────────────
const BRAND_COLS = [
  { id: 'brand',      label: 'Brand',         w: 220 },
  { id: 'ads',        label: 'Ads',           w: 110, align: 'left'  },
  { id: 'fbPages',    label: 'FB Pages',      w: 74,  align: 'right' },
  { id: 'avgFbLikes', label: 'Avg. FB likes', w: 98,  align: 'right' },
  { id: 'sales',      label: 'Sales 30d',     w: 150, align: 'right' },
  { id: 'estSpend',   label: 'Est. spend',    w: 150, align: 'right' },
  { id: 'visitors',   label: 'Visitors 6m',   w: 122, align: 'right' },
  { id: 'topCountry', label: 'Top countries', w: 120, align: 'right' },
  { id: 'trustpilot', label: 'Trustpilot',    w: 86,  align: 'right' },
  { id: 'actions',    label: '',              w: 44,  align: 'right' },
];

const BRAND_COL_FIELDS_DEFAULT = {
  ads:         true,
  fbPages:     true,
  avgFbLikes:  true,
  sales:       true,
  estSpend:    true,
  visitors:    true,
  topCountry:  true,
  trustpilot:  true,
};

const BRAND_COL_FIELD_OPTIONS = [
  { id: 'ads',         label: 'Ads (active / total)', icon: 'sparkles' },
  { id: 'fbPages',     label: 'FB Pages',             icon: 'globe'    },
  { id: 'avgFbLikes',  label: 'Avg. FB likes',        icon: 'heart'    },
  { id: 'sales',       label: 'Sales last 30d',       icon: 'wallet'   },
  { id: 'estSpend',    label: 'Est. spend',           icon: 'trend-up' },
  { id: 'visitors',    label: 'Visitors 6m',          icon: 'users'    },
  { id: 'topCountry',  label: 'Top countries',        icon: 'flag'     },
  { id: 'trustpilot',  label: 'Trustpilot',           icon: 'star'     },
];

// ── Sort options ──────────────────────────────────────────────────────────────
const BRAND_SORT_OPTIONS = [
  { id: 'active',     label: 'Active ads',  icon: 'sparkles', key: (b) => b.active },
  { id: 'total',      label: 'Total ads',   icon: 'copy',     key: (b) => b.total },
  { id: 'spend',      label: 'Est. spend',  icon: 'wallet',   key: (b) => b.spend },
  { id: 'sales',      label: 'Sales 30d',   icon: 'wallet',   key: (b) => b.salesLast30d },
  { id: 'visitors',   label: 'Visitors 6m', icon: 'users',    key: (b) => (b.visitorsLast6m || []).reduce((a, v) => a + v, 0) },
  { id: 'trustpilot', label: 'Trustpilot',  icon: 'star',     key: (b) => b.trustpilot?.score || 0 },
  { id: 'name',       label: 'Brand (A–Z)', icon: 'building', key: (b) => b.name.toLowerCase() },
];

const sortBrands = (brands, sortId, direction) => {
  const opt = BRAND_SORT_OPTIONS.find(o => o.id === sortId) || BRAND_SORT_OPTIONS[0];
  const sign = direction === 'asc' ? 1 : -1;
  return [...brands].sort((a, b) => {
    const ka = opt.key(a), kb = opt.key(b);
    if (typeof ka === 'string') return sign * ka.localeCompare(kb);
    return sign * (ka - kb);
  });
};


// ── Cell renderer ─────────────────────────────────────────────────────────────
const renderBrandCell = (colId, b) => {
  switch (colId) {

    case 'brand':
      return (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <BrandChip name={b.name} size={32} square/>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontWeight: 500, fontSize: 13, color: 'var(--text)', display: 'flex', alignItems: 'center', gap: 4 }}>
              <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{b.name}</span>
              {b.verified && <Icon name="check-circle" size={12} style={{ color: 'var(--accent)', flexShrink: 0 }}/>}
            </div>
            <div style={{ fontSize: 11, color: 'var(--text-faint)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{b.handle}</div>
          </div>
        </div>
      );

    case 'ads':
      return (
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
          <span style={{ width: 7, height: 7, borderRadius: 999, background: '#10B981', flexShrink: 0 }}/>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>{b.active}</span>
          <span style={{ color: 'var(--text-faint)', fontSize: 12, lineHeight: 1 }}>/</span>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-2)' }}>{b.total}</span>
        </div>
      );

    case 'fbPages':
      return <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--text-2)' }}>{b.fbPages}</span>;

    case 'avgFbLikes':
      return <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--text-2)' }}>{fmtB(b.avgFbLikes)}</span>;

    case 'sales': {
      const data = genDailyData(b.id.charCodeAt(1) * 7 + 3, b.salesLast30d / 30, 30);
      return (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'flex-end' }}>
          <MiniAreaChart data={data} labels={DAY_LABELS_30} width={55} height={28}
            formatY={(v) => `€${fmtB(Math.round(v))}`}/>
          <div style={{ textAlign: 'right', flexShrink: 0 }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 600, color: 'var(--text)' }}>€{fmtB(b.salesLast30d)}</div>
            <div style={{ fontSize: 9, color: 'var(--text-faint)', marginTop: 1 }}>last 30d</div>
          </div>
        </div>
      );
    }

    case 'estSpend': {
      const data = genDailyData(b.id.charCodeAt(1) * 13 + 7, b.spend / 30, 30);
      return (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'flex-end' }}>
          <MiniAreaChart data={data} labels={DAY_LABELS_30} width={55} height={28}
            formatY={(v) => `€${fmtB(Math.round(v))}`}/>
          <div style={{ textAlign: 'right', flexShrink: 0 }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 600, color: 'var(--text)' }}>€{fmtB(b.spend)}</div>
            <div style={{ fontSize: 9, color: 'var(--text-faint)', marginTop: 1 }}>last 30d</div>
          </div>
        </div>
      );
    }

    case 'visitors': {
      const data = b.visitorsLast6m || [];
      return (
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, justifyContent: 'flex-end' }}>
          <MiniAreaChart data={data} labels={MONTH_LABELS_6} width={50} height={20}
            formatY={(v) => fmtB(Math.round(v))}/>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 500, color: 'var(--text)' }}>
            {fmtB(data[data.length - 1])}
          </span>
        </div>
      );
    }

    case 'topCountry':
      return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 3, alignItems: 'flex-end' }}>
          {(b.topCountries || []).map(({ c, pct }) => (
            <div key={c} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
              <Icon name={`flag-${c}`} size={12}/>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-2)', minWidth: 26, textAlign: 'right' }}>{pct}%</span>
            </div>
          ))}
        </div>
      );

    case 'trustpilot': {
      const score = b.trustpilot?.score ?? 0;
      return (
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, justifyContent: 'flex-end' }}>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 500, color: 'var(--text)' }}>{score.toFixed(1)}</span>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="#00B67A" stroke="none">
            <path d="m12 3 2.6 5.5 6 .9-4.3 4.2 1 6-5.3-2.8-5.3 2.8 1-6L3.4 9.4l6-.9z"/>
          </svg>
        </div>
      );
    }

    default: return null;
  }
};

// ── Row context menu ──────────────────────────────────────────────────────────
const BRAND_MENU_ITEMS = [
  { id: 'view',      label: 'View brand',      icon: 'building'  },
  { id: 'ads',       label: 'View ads',        icon: 'copy'      },
  { id: 'watchlist', label: 'Add to watchlist', icon: 'bookmark' },
  { id: 'export',    label: 'Export data',     icon: 'download'  },
  { id: 'sep' },
  { id: 'remove',    label: 'Remove brand',    icon: 'trash',    danger: true },
];

const BrandRowMenu = ({ brand, onBrandSelect }) => {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    const close = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, [open]);

  const handleItem = (e, id) => {
    e.stopPropagation();
    setOpen(false);
    if (id === 'view') onBrandSelect && onBrandSelect(brand.id);
  };

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button
        className="btn btn-ghost btn-icon"
        style={{ width: 28, height: 28 }}
        onClick={(e) => { e.stopPropagation(); setOpen(v => !v); }}
      >
        <Icon name="more-h" size={16}/>
      </button>
      {open && (
        <div style={{
          position: 'absolute', right: 0, top: 'calc(100% + 4px)',
          background: 'var(--bg-surface)',
          border: '1px solid var(--border)',
          borderRadius: 10,
          boxShadow: '0 8px 24px rgba(14,18,27,0.16)',
          padding: 4,
          minWidth: 168,
          zIndex: 200,
        }}>
          {BRAND_MENU_ITEMS.map((item, i) =>
            item.id === 'sep'
              ? <div key={i} style={{ height: 1, background: 'var(--border-soft)', margin: '3px 0' }}/>
              : (
                <button
                  key={item.id}
                  onClick={(e) => handleItem(e, item.id)}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 8,
                    width: '100%', padding: '7px 10px', borderRadius: 7,
                    border: 'none', cursor: 'pointer', background: 'transparent',
                    color: item.danger ? 'var(--danger)' : 'var(--text)',
                    fontSize: 13, textAlign: 'left',
                  }}
                  onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-soft)'}
                  onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
                >
                  <Icon name={item.icon} size={14}
                    style={{ color: item.danger ? 'var(--danger)' : 'var(--text-faint)', flexShrink: 0 }}/>
                  {item.label}
                </button>
              )
          )}
        </div>
      )}
    </div>
  );
};

// ── Main component ────────────────────────────────────────────────────────────
const BrandsV3 = ({ brandId, onBrandSelect, onBack }) => {
  if (brandId) {
    const brand = (BRANDS_V3 || []).find(b => b.id === brandId);
    if (brand) return <BrandDetailV3 brand={brand} onBack={onBack}/>;
  }

  const [search, setSearch]         = React.useState('');
  const [filterMode, setFilterMode] = React.useState('all');
  const [activeChip, setActiveChip] = React.useState([]);
  const [sort, setSort]             = React.useState('active');
  const [sortDir, setSortDir]       = React.useState('desc');
  const [colFields, setColFields]   = React.useState(BRAND_COL_FIELDS_DEFAULT);

  const chips = [
    { id: 'fashion', label: 'Fashion' },
    { id: 'beauty',  label: 'Beauty'  },
    { id: 'fr',      label: 'France',        icon: 'flag-fr' },
    { id: 'us',      label: 'United States', icon: 'flag-us' },
  ];
  const toggle = (id) => setActiveChip(a => a.includes(id) ? a.filter(x => x !== id) : [...a, id]);

  const visibleBrands = sortBrands(
    (BRANDS_V3 || []).filter(b =>
      !search ||
      b.name.toLowerCase().includes(search.toLowerCase()) ||
      b.handle.toLowerCase().includes(search.toLowerCase())
    ),
    sort, sortDir,
  );

  const visibleCols = BRAND_COLS.filter(c =>
    c.id === 'brand' || c.id === 'actions' || colFields[c.id]
  );

  return (
    <>
      <PageHeader
        icon="building"
        title="Brands"
        subtitle="Track competitors and their ad libraries"
        right={
          <>
            <button className="btn btn-stroke btn-sm"><Icon name="play-line" size={14}/> Tutorial</button>
            <button className="btn btn-night btn-sm"><Icon name="plus" size={14}/> Add brand</button>
          </>
        }
      />

      <FilterStripV3
        filterMode={filterMode} onFilterMode={setFilterMode}
        search={search} onSearch={setSearch}
        chips={chips} activeChip={activeChip} onChip={toggle}
      />

      <SortRowV3
        count={visibleBrands.length}
        countLabel="brands"
        sort={sort}
        sortOptions={BRAND_SORT_OPTIONS}
        direction={sortDir}
        onSort={setSort}
        onDirection={setSortDir}
        cardFields={colFields}
        cardFieldOptions={BRAND_COL_FIELD_OPTIONS}
        onCardFieldsChange={setColFields}
        cardFieldsTitle="Show columns"
      />

      <div style={{ padding: 24, flex: 1, overflow: 'auto' }} className="scroll">
        <div className="card" style={{ padding: 8 }}>
          <div style={{ overflowX: 'auto' }} className="scroll">

            {/* Column header */}
            <div style={{
              display: 'flex',
              background: 'var(--bg-soft)',
              borderRadius: 8, padding: '0 4px',
              height: 34, alignItems: 'center',
              fontSize: 11, color: 'var(--text-faint)', fontWeight: 600,
              letterSpacing: '0.04em', textTransform: 'uppercase',
            }}>
              {visibleCols.map(c => (
                <div key={c.id} style={{
                  ...(c.id === 'brand' ? { flex: 1, minWidth: c.w } : { width: c.w, flexShrink: 0 }),
                  padding: '0 10px',
                  textAlign: c.align || 'left',
                }}>
                  {c.label}
                </div>
              ))}
            </div>

            {/* Rows — taller to fit 3-country stack */}
            {visibleBrands.map((b) => (
              <div key={b.id} style={{
                display: 'flex', alignItems: 'center',
                minHeight: 66, padding: '6px 4px',
                borderRadius: 10, cursor: 'pointer',
                transition: 'background .12s',
              }}
              onClick={() => onBrandSelect && onBrandSelect(b.id)}
              onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-soft)'}
              onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
              >
                {visibleCols.map(c => (
                  <div key={c.id} style={{
                    ...(c.id === 'brand' ? { flex: 1, minWidth: c.w } : { width: c.w, flexShrink: 0 }),
                    padding: '0 10px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: c.align === 'right' ? 'flex-end' : 'flex-start',
                  }}>
                    {c.id === 'actions'
                      ? <BrandRowMenu brand={b} onBrandSelect={onBrandSelect}/>
                      : renderBrandCell(c.id, b)}
                  </div>
                ))}
              </div>
            ))}
          </div>
        </div>
      </div>
    </>
  );
};

Object.assign(window, { BrandsV3, BRAND_SORT_OPTIONS, BRAND_COL_FIELDS_DEFAULT, BRAND_COL_FIELD_OPTIONS, sortBrands });
