/* WPSiteBeam Scanner — Brand Kit Tab
   Auto-split from Scanner.jsx.
*/
(function () {
  'use strict';
  const ScanEmptyState = window.ScanEmptyState;
  const Icon = window.Icon;

function ScannerBrandKitTab({ data, payloads }) {
  /* Ported from v1 scanner.html renderBrandKit (line 3736).
     Renders Brand Identity grid using fields Railway /brain/scan returns
     + client-side enrichment (logo, colors, fonts from enrichBrandData).
     Layout: 2-column split — left = Logo preview, right = field grid.
     Colors/Typography sections follow, then (future) Site Counts + Canva export. */
  if (!data || !data.site) {
    return <ScanEmptyState tab="brand kit" reason="Run a scan to populate brand identity data." />;
  }

  const tech = data.tech || {};
  /* socials + contact variables removed — Contact tab owns that data now */
  const em = (label) => <span style={{ color:'var(--muted)', fontSize:'.78rem', fontStyle:'italic' }}>— {label}</span>;

  /* Session A: primary email/phone with dynamic labels (from ScannerData normalize).
     Labels like "Sales Department" / "Main Office Voice" come from contact extraction. */
  const primaryEmail = data.primaryEmail || null;
  const primaryEmailLabel = data.primaryEmailLabel || 'Primary Email';
  const primaryPhone = data.primaryPhone || null;
  const primaryPhoneLabel = data.primaryPhoneLabel || 'Primary Phone';

  /* Session A: "Also Detected" — other platforms matched by signature scan.
     Skip the primary (index 0) since that's already shown as Website Builder. */
  const alsoDetected = (() => {
    const dp = tech.detectedPlatforms;
    if (!Array.isArray(dp) || dp.length < 2) return null;
    return dp.slice(1, 4).map(p => {
      const name = p.name || p.id || 'unknown';
      const conf = p.confidence != null ? String(p.confidence) : null;
      return conf ? `${name} (${conf})` : name;
    }).join(', ');
  })();

  /* Session A: logo image with onerror fallback — tries logoUrl → ogImage → initial chip.

     v1.3.8 patch h10: route ALL external images through Railway's
     /proxy/image endpoint. CD's host (WPMU Dev) sends a
     Cross-Origin-Resource-Policy: same-origin header on its uploaded
     images, which causes the browser to block <img src="...">  loads
     from app.wpsitebeam.io with ERR_BLOCKED_BY_RESPONSE.NotSameOrigin.
     Most modern WP hosts (Kinsta, WP Engine, Cloudways) do this by
     default. The /proxy/image endpoint already sets
     Cross-Origin-Resource-Policy: cross-origin on its responses, so
     proxied images render correctly. We only proxy http(s) URLs —
     data: URIs go through unchanged. */
  const _RAILWAY_API = (typeof window !== 'undefined' && window.WPSB_API)
    || 'https://wpsitebeam-railway-api-production.up.railway.app';
  function proxyImg(rawUrl) {
    if (!rawUrl) return null;
    if (rawUrl.startsWith('data:')) return rawUrl;
    if (!/^https?:\/\//i.test(rawUrl)) return rawUrl;
    return _RAILWAY_API + '/proxy/image?url=' + encodeURIComponent(rawUrl);
  }
  const [logoBg, setLogoBg] = useState('white'); // white | black | auto | checker (default white — best for transparent logos)
  const rawLogoSrc = data.logoUrl || data.ogImage || null;
  const logoSrc = proxyImg(rawLogoSrc);
  const faviconSrc = proxyImg(data.faviconUrl);
  const initialChar = (data.logo && data.logo !== '•') ? data.logo : (data.site || '?').charAt(0).toUpperCase();

  /* Brand Identity field rows — brand/contact only. Removed per feedback:
     Scan Date (redundant), Pages Scanned (in Sitemap tab). Tech info moved
     to Tech/DNS tab previously. */
  const rows = [
    ['Site Name', data.site],
    ['Site URL', <a href={data.siteUrl} target="_blank" rel="noopener noreferrer" style={{ color:'var(--beam)' }}>{data.siteUrl}</a>],
    [primaryEmailLabel, primaryEmail ? <a href={`mailto:${primaryEmail}`} style={{ color:'var(--beam)' }}>{primaryEmail}</a> : em('not found on scanned pages')],
    [primaryPhoneLabel, primaryPhone ? <a href={`tel:${primaryPhone.replace(/\D/g,'')}`} style={{ color:'var(--beam)' }}>{primaryPhone}</a> : em('not found on scanned pages')],
  ];

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
      {/* 2026-05-20 — In-tab toolbar removed. Brand Kit (PDF) export now
          lives in the global Actions row in core.jsx alongside JSON / SEO /
          Site Builder. Previously, the in-tab button called bare
          `exportBrandKitPdf(data)` which fell through this IIFE scope to
          window.exportBrandKitPdf — a Pages2.jsx function with hardcoded
          ACME placeholder branding that ignored the data param. Bug
          discovered when tms-inc.us scan exported a PDF full of Acme/
          Sequoia/YC placeholder content. TXT export removed entirely per
          UX feedback: nearly empty payloads were misleading. */}

      {/* Brand Identity + Typography side-by-side (50/50) — consolidated
          per UX feedback. Removed SiteBuilder platform tag from Brand
          Identity header (now in Tech/DNS). Logo stacks above fields
          since the card is now 50% width. */}
      <div className="grid grid-2" style={{ gap:14 }}>
      <div className="card">
        <div className="card-head">
          <h2 className="card-title">Brand Identity</h2>
        </div>
        <div className="card-body">
          {/* Logo (+ favicon if present) on the LEFT, fields grid on the RIGHT.
              Per UX feedback: fixed columns so fields aren't pushed down by
              the logo's height. If favicon was extracted (data.faviconUrl),
              it stacks below the main logo as a smaller preview. */}
          <div style={{ display:'grid', gridTemplateColumns:'100px 1fr', gap:18, alignItems:'start' }}>
            {/* Brand-asset column — logo + optional favicon */}
            <div style={{ display:'flex', flexDirection:'column', gap:12, alignItems:'center' }}>
              {/* Logo tile (100x100) */}
              <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:6 }}>
                <div
                  data-wpsb-logo-state={logoSrc ? (data.logoUrl ? 'logo' : 'og') : 'missing'}
                  data-wpsb-logo-src={logoSrc || ''}
                  data-wpsb-logo-raw={data.logoUrl || ''}
                  data-wpsb-favicon-raw={data.faviconUrl || ''}
                  style={{
                  width:100, height:100, borderRadius:10, border:'1px solid var(--border)',
                  background: logoBg === 'white' ? '#ffffff'
                            : logoBg === 'black' ? '#111111'
                            : 'var(--surface-2)',
                  display:'flex', alignItems:'center', justifyContent:'center',
                  overflow:'hidden', position:'relative', cursor: logoSrc ? 'pointer' : 'default',
                  transition:'background .2s',
                }}
                  title={logoSrc ? 'Click to cycle background: auto → white → black → checkerboard' : ''}
                  onClick={() => {
                    if (!logoSrc) return;
                    setLogoBg(b => b === 'auto' ? 'white' : b === 'white' ? 'black' : b === 'black' ? 'checker' : 'auto');
                  }}
                >
                  {logoSrc ? (
                    <img
                      src={logoSrc}
                      alt={`${data.site} logo`}
                      style={{
                        maxWidth:'80%', maxHeight:'80%', objectFit:'contain',
                        ...(logoBg === 'checker' ? {
                          background: 'repeating-conic-gradient(#ccc 0% 25%, #fff 0% 50%) 0 0 / 12px 12px',
                          borderRadius: 4,
                        } : {}),
                      }}
                      onError={(e) => {
                        /* On image load failure, replace with initial-chip fallback.
                           v1.3.8 patch h5: log the failed URL.
                           v1.3.8 patch h9: ALSO render the failed URL in the tile
                           below the initial char so the failure is self-diagnosing
                           from a screenshot — no DevTools needed. */
                        try {
                          console.warn('[WPSB BrandKit] Logo image failed to load:', {
                            src: e?.target?.src,
                            naturalWidth: e?.target?.naturalWidth,
                            naturalHeight: e?.target?.naturalHeight,
                            data_logoUrl: data.logoUrl,
                            data_ogImage: data.ogImage,
                            data_faviconUrl: data.faviconUrl,
                          });
                        } catch (warnErr) { /* swallow */ }
                        const parent = e.target.parentElement;
                        if (!parent) return;
                        const ch = initialChar;
                        const failedUrl = (e?.target?.src || '').replace(/^https?:\/\//, '');
                        const truncated = failedUrl.length > 30 ? failedUrl.slice(0, 14) + '…' + failedUrl.slice(-14) : failedUrl;
                        parent.innerHTML =
                          '<div style="display:flex;flex-direction:column;align-items:center;gap:4px;padding:4px;text-align:center">' +
                            '<div style="font-family:var(--font-display,var(--font-mono));font-size:1.6rem;font-weight:700;color:var(--beam);opacity:.6;line-height:1">' + ch + '</div>' +
                            '<div style="font-size:.45rem;color:var(--dim);font-family:var(--font-mono);word-break:break-all;line-height:1.2;opacity:.7">' + truncated + '</div>' +
                          '</div>';
                      }}
                    />
                  ) : (
                    <div style={{
                      display:'flex', flexDirection:'column', alignItems:'center', gap:4, padding:4, textAlign:'center',
                    }}>
                      <div style={{
                        fontFamily:'var(--font-display, var(--font-mono))', fontSize:'1.6rem', fontWeight:700,
                        color:'var(--beam)', opacity:.6, lineHeight:1,
                      }}>{initialChar}</div>
                      <div style={{ fontSize:'.45rem', color:'var(--dim)', fontFamily:'var(--font-mono)', lineHeight:1.2, opacity:.7 }}>
                        no logo extracted
                      </div>
                    </div>
                  )}
                </div>
                <div style={{ textAlign:'center' }}>
                  <div style={{ fontSize:'.68rem', color:'var(--dim)', fontFamily:'var(--font-mono)', letterSpacing:'.08em', fontWeight:600 }}>
                    {logoSrc ? (data.logoUrl ? 'LOGO' : 'OG:IMAGE') : 'NO LOGO'}
                  </div>
                  {logoSrc && (
                    <div style={{ fontSize:'.62rem', color:'#7b8fa8', marginTop:3, lineHeight:1.3 }}>
                      Click to toggle bg
                    </div>
                  )}
                </div>
              </div>

              {/* Favicon tile (48x48) — only renders if a favicon URL was
                  extracted by the scanner (data.faviconUrl). Browsers serve
                  favicons at predictable paths (/favicon.ico, apple-touch-icon,
                  <link rel="icon">). ScannerData.jsx already extracts it. */}
              {data.faviconUrl && (
                <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:6 }}>
                  <div
                    data-wpsb-favicon-state="present"
                    data-wpsb-favicon-src={data.faviconUrl}
                    style={{
                    width:48, height:48, borderRadius:8, border:'1px solid var(--border)',
                    background: logoBg === 'white' ? '#ffffff'
                              : logoBg === 'black' ? '#111111'
                              : 'var(--surface-2)',
                    display:'flex', alignItems:'center', justifyContent:'center',
                    overflow:'hidden', cursor:'pointer', transition:'background .2s',
                  }}
                    title="Click logo to cycle background"
                  >
                    <img
                      src={faviconSrc}
                      alt={`${data.site} favicon`}
                      style={{
                        maxWidth:'80%', maxHeight:'80%', objectFit:'contain',
                        ...(logoBg === 'checker' ? {
                          background: 'repeating-conic-gradient(#ccc 0% 25%, #fff 0% 50%) 0 0 / 12px 12px',
                          borderRadius: 4,
                        } : {}),
                      }}
                      onError={(e) => {
                        /* On failure, replace with a subtle missing-icon placeholder.
                           v1.3.8 patch h5: log details so we can diagnose load failures. */
                        try {
                          console.warn('[WPSB BrandKit] Favicon image failed to load:', {
                            src: e?.target?.src,
                            data_faviconUrl: data.faviconUrl,
                          });
                        } catch (warnErr) { /* swallow */ }
                        const parent = e.target.parentElement;
                        if (!parent) return;
                        parent.innerHTML = `<div style="font-size:.58rem;color:var(--dim);font-family:var(--font-mono);letter-spacing:.06em">N/A</div>`;
                      }}
                    />
                  </div>
                  <div style={{ fontSize:'.68rem', color:'var(--dim)', fontFamily:'var(--font-mono)', letterSpacing:'.08em', textAlign:'center', fontWeight:600 }}>
                    FAVICON
                  </div>
                </div>
              )}
            </div>

            {/* Fields grid — 2 columns (label/value), right side of the card */}
            <div style={{ display:'grid', gridTemplateColumns:'auto 1fr', gap:'8px 16px', fontSize:'.82rem', alignItems:'baseline', minWidth:0 }}>
              {rows.map(([label, val], i) => (
                <React.Fragment key={i}>
                  <span style={{ color:'var(--dim)', fontFamily:'var(--font-mono)', fontSize:'.7rem', whiteSpace:'nowrap' }}>{label}:</span>
                  <span style={{ color:'var(--text)', wordBreak:'break-word', minWidth:0 }}>{val}</span>
                </React.Fragment>
              ))}
            </div>
          </div>
          {/* end logo+fields grid */}

          {/* Social PROFILES removed from Brand Identity — the Contact tab
              has a dedicated "Social channels" card. Keeping them here
              would duplicate data across two tabs. */}

          {/* Plugins list removed — moved to Tech/DNS tab where it belongs
              (tech stack, not brand identity). */}
        </div>
      </div>

      {/* Typography — sits in grid-2 next to Brand Identity at 50% each */}
      <div className="card">
        <div className="card-head">
          <h2 className="card-title">Typography</h2>
          <span className="tag">{(data.fonts || []).length} found</span>
        </div>
        {/* 2026-05-20 — overflow-x hidden + table-layout: fixed prevents
            horizontal scroll on narrow cards. Source column truncates with
            ellipsis rather than expanding the table beyond the card width. */}
        <div className="card-body" style={{ padding: 0, overflowX: 'hidden' }}>
          {(data.fonts || []).length === 0 ? (
            <div style={{ padding:'20px 14px', textAlign:'center', color:'var(--muted)', fontSize:'.82rem' }}>
              No fonts detected in the site's CSS. If the site uses system fonts only, this section may be empty.
            </div>
          ) : (
            <table className="table" style={{ tableLayout: 'fixed', width: '100%' }}>
              <thead>
                <tr>
                  <th scope="col" style={{ width:'55%' }}>Font</th>
                  <th scope="col" style={{ width:'30%' }}>Source</th>
                  <th scope="col" style={{ width:'15%', textAlign:'right' }}>Uses</th>
                </tr>
              </thead>
              <tbody>
                {data.fonts.map((f, i) => {
                  const name = f.name || f;
                  const src = f.src || f.source || 'CSS';
                  const uses = f.uses || 0;
                  return (
                    <tr key={i}>
                      <td style={{ overflow:'hidden' }}>
                        <div style={{ display:'flex', flexDirection:'column', gap:2, minWidth:0 }}>
                          <span style={{ fontFamily: `"${name}", system-ui, sans-serif`, fontSize:'1rem', color:'var(--text)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
                            {name}
                          </span>
                          {f.isSystem && (
                            <span style={{ fontSize:'.62rem', color:'var(--dim)', fontFamily:'var(--font-mono)', letterSpacing:'.06em' }}>
                              SYSTEM FONT
                            </span>
                          )}
                          {Array.isArray(f.weights) && f.weights.length > 0 && (
                            <span style={{ fontSize:'.68rem', color:'var(--muted)', fontFamily:'var(--font-mono)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
                              {f.weights.join(', ')}
                            </span>
                          )}
                        </div>
                      </td>
                      <td style={{ fontSize:'.72rem', color:'var(--muted)', fontFamily:'var(--font-mono)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }} title={src}>{src}</td>
                      <td style={{ textAlign:'right', fontSize:'.72rem', color:'var(--muted)', fontFamily:'var(--font-mono)' }}>{uses > 0 ? uses : '—'}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </div>
      </div>
      </div>
      {/* end grid-2: Brand Identity + Typography */}

      {/* Colors — full width below the 2-column grid so swatches have room */}
      <div className="card">
        <div className="card-head">
          <h2 className="card-title">Colors</h2>
          <span className="tag">{(data.colors || []).length} found</span>
        </div>
        <div className="card-body">
          {(data.colors || []).length === 0 ? (
            <div style={{ padding:'20px 0', textAlign:'center', color:'var(--muted)', fontSize:'.82rem' }}>
              No colors extracted. This can happen if the site's stylesheets didn't load or weren't reachable during the scan.
            </div>
          ) : (
            <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(110px, 1fr))', gap:10 }}>
              {data.colors.map((c, i) => {
                const hex = c.hex || c;
                const name = c.name || hex.toUpperCase();
                return (
                  <button
                    key={i}
                    onClick={() => window.wpsbCopy && window.wpsbCopy(hex, `Copied ${hex}`)}
                    style={{
                      display:'flex', flexDirection:'column', gap:6,
                      padding:0, border:'1px solid var(--border)', borderRadius:8,
                      overflow:'hidden', background:'var(--surface-2)', cursor:'pointer',
                      textAlign:'left', font:'inherit', color:'inherit',
                    }}
                    aria-label={`Copy color ${hex}`}
                    title={`Click to copy ${hex}`}
                  >
                    <div style={{ height:56, background:hex, borderBottom:'1px solid var(--border)' }} />
                    <div style={{ padding:'6px 8px 8px', display:'flex', flexDirection:'column', gap:2 }}>
                      <span className="mono" style={{ fontSize:'.72rem', color:'var(--text)', fontWeight:600 }}>{hex}</span>
                      {c.role && c.role !== 'detected' && (
                        <span style={{ fontSize:'.65rem', color:'var(--dim)', fontFamily:'var(--font-mono)', letterSpacing:'.04em' }}>
                          {c.role.toUpperCase()}
                        </span>
                      )}
                    </div>
                  </button>
                );
              })}
            </div>
          )}
        </div>
      </div>

      {/* Icon Libraries — always renders. Currently shows empty-state because
          icon-library detection isn't in the scan engine yet (data.icons is a
          stub count from ScannerData normalize). Phase 2 will plumb real
          detection (Font Awesome, Heroicons, Lucide, Material Icons, custom
          SVG sprites) and populate {data.iconLibraries: [{name, version,
          source, usage}]} for this section to render. */}
      <div className="card">
        <div className="card-head">
          <h2 className="card-title">Icon Libraries</h2>
          {(data.icons || 0) > 0 && <span className="tag">{data.icons} detected</span>}
        </div>
        <div className="card-body" style={{ padding: 0 }}>
          {(data.icons || 0) === 0 ? (
            <ScanEmptyState
              bare
              tab="icon libraries"
              reason="Icon library detection (Font Awesome, Heroicons, Lucide, Material, custom SVG sprites) is queued for a future scan engine update. The data will surface here automatically once available."
            />
          ) : (
            <div style={{ padding: 16 }}>
              {/* Renders only after Phase 2 plumbs real detection through.
                  data.iconLibraries shape: [{name, version?, source?, sample?:string[]}] */}
              {Array.isArray(data.iconLibraries) && data.iconLibraries.length > 0 ? (
                <table className="table">
                  <thead>
                    <tr>
                      <th scope="col">Library</th>
                      <th scope="col" style={{ width:120 }}>Version</th>
                      <th scope="col" style={{ width:160 }}>Source</th>
                      <th scope="col" style={{ width:80, textAlign:'right' }}>Usage</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.iconLibraries.map((lib, i) => (
                      <tr key={i}>
                        <td style={{ fontWeight:600 }}>{lib.name || 'Unknown'}</td>
                        <td className="mono" style={{ fontSize:'.72rem', color:'var(--dim)' }}>{lib.version || '—'}</td>
                        <td className="mono" style={{ fontSize:'.72rem', color:'var(--dim)' }}>{lib.source || '—'}</td>
                        <td className="mono" style={{ fontSize:'.72rem', textAlign:'right' }}>{lib.usage ?? '—'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              ) : (
                <div style={{ padding:'12px 4px', color:'var(--muted)', fontSize:'.82rem' }}>
                  {data.icons} icon library reference{data.icons === 1 ? '' : 's'} detected. Per-library breakdown pending scan engine update.
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Typography moved up into the Brand Identity/Typography grid-2.
          Colors + Icon Libraries sit full-width below that 50/50 row. */}
    </div>
  );
}


window.ScannerBrandKitTab = ScannerBrandKitTab;
})();
