/* Blackstock shared primitives */

/* Hook: detecta viewport mobile (≤ 720px) y se actualiza al rotar/redimensionar.
 * Se usa para decidir si renderizar HomePage (desktop) o HomeMobile.
 * SSR-safe: durante el primer render server-side devuelve false; en cliente
 * se sincroniza tras montaje. */
const useIsMobile = (breakpoint = 720) => {
  const [isMobile, setIsMobile] = React.useState(() => {
    if (typeof window === 'undefined') return false;
    return window.matchMedia(`(max-width: ${breakpoint}px)`).matches;
  });
  React.useEffect(() => {
    const mql = window.matchMedia(`(max-width: ${breakpoint}px)`);
    const onChange = (e) => setIsMobile(e.matches);
    setIsMobile(mql.matches);
    if (mql.addEventListener) mql.addEventListener('change', onChange);
    else mql.addListener(onChange); // Safari < 14
    return () => {
      if (mql.removeEventListener) mql.removeEventListener('change', onChange);
      else mql.removeListener(onChange);
    };
  }, [breakpoint]);
  return isMobile;
};
window.useIsMobile = useIsMobile;

const LogoMark = ({ size = 22 }) => (
  <svg width={size} height={size} viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ display: 'block' }}>
    <defs>
      <linearGradient id={`bs-acid-${size}`} x1="28" y1="18" x2="100" y2="106" gradientUnits="userSpaceOnUse">
        <stop offset="0" stopColor="#F3FFAA" />
        <stop offset="0.48" stopColor="#D6FF4D" />
        <stop offset="1" stopColor="#B8DE34" />
      </linearGradient>
    </defs>
    <g fill={`url(#bs-acid-${size})`}>
      <path d="M64 14 92 31.5V43L64 26.5 36 43V31.5L64 14Z" />
      <path d="M64 38 99 59.5V72L64 51.5 29 72V59.5L64 38Z" />
      <path d="M64 64 104 87.5V100L64 76.5 24 100V87.5L64 64Z" />
    </g>
  </svg>
);

const Logo = ({ size = 22 }) => (
  <a href="#" className="bs-logo" onClick={(e) => e.preventDefault()}>
    <LogoMark size={size} />
    <span>BLACK<span className="stock">STOCK</span></span>
  </a>
);

const Nav = ({ activePage = 'home', onNavigate = () => {} }) => {
  const isMobile = useIsMobile();
  const items = [
    { id: 'home', label: 'Sistema' },
    { id: 'product', label: 'Dentro' },
    { id: 'anty', label: 'Anty', accent: true },
    { id: 'pricing', label: 'Planes' },
    { id: 'home', label: 'Casos', anchor: '#casos' },
    { id: 'home', label: 'FAQ', anchor: '#faq' },
  ];
  return (
    <nav data-bs-navbar style={{
      position: 'sticky', top: 0, zIndex: 50,
      borderBottom: '1px solid var(--line)',
      background: 'rgba(10, 11, 7, 0.55)',
      backdropFilter: 'saturate(160%) blur(14px)',
      WebkitBackdropFilter: 'saturate(160%) blur(14px)',
    }}>
      <div className="bs-container" style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        height: isMobile ? 56 : 64,
        gap: 12,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: isMobile ? 0 : 32, minWidth: 0 }}>
          <Logo />
          {!isMobile && (
            <div className="bs-pill" style={{ height: 22, fontSize: 10, padding: '0 8px' }}>
              <span className="bs-dot live"></span>
              <span>v3.2 · LIVE</span>
            </div>
          )}
        </div>

        {!isMobile && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            {items.map((item, i) => {
              const isActive = activePage === item.id && !item.anchor;
              const baseColor = item.accent ? 'var(--acid)' : (isActive ? 'var(--fg)' : 'var(--fg-3)');
              return (
                <button
                  key={i}
                  onClick={() => onNavigate(item.id)}
                  className="bs-nav-link"
                  style={{
                    background: 'transparent', border: 'none',
                    color: baseColor,
                    fontFamily: 'var(--font-display)',
                    fontWeight: item.accent ? 600 : 500, fontSize: 14, letterSpacing: '-0.005em',
                    padding: '8px 14px', borderRadius: 999, cursor: 'pointer',
                    transition: 'color .15s ease',
                    display: 'inline-flex', alignItems: 'center', gap: 6,
                  }}
                  onMouseEnter={(e) => e.currentTarget.style.color = item.accent ? 'var(--acid)' : 'var(--fg)'}
                  onMouseLeave={(e) => e.currentTarget.style.color = baseColor}
                >
                  {item.accent && (
                    <span aria-hidden="true" style={{
                      width: 5, height: 5, borderRadius: '50%',
                      background: 'var(--acid)',
                      boxShadow: '0 0 8px var(--acid)',
                    }} />
                  )}
                  {item.label}
                </button>
              );
            })}
          </div>
        )}

        <div style={{ display: 'flex', alignItems: 'center', gap: isMobile ? 6 : 10 }}>
          {!isMobile && (
            <button
              onClick={() => window.bsOpenDemo && window.bsOpenDemo()}
              className="bs-btn bs-btn-ghost bs-btn-sm"
              style={{ height: 36, fontSize: 13 }}
            >
              Ver demo
            </button>
          )}
          <UserAuthZone onNavigate={onNavigate} />
        </div>
      </div>
    </nav>
  );
};

/* Bloque del navbar para auth: cuando NO hay sesión muestra "Empezar".
 * Cuando hay sesión muestra avatar + dropdown (Portal/Academia/Panel/Logout).
 * Se suscribe al evento 'bs:session-changed' para refrescar al instante.
 */
const UserAuthZone = ({ onNavigate }) => {
  const [session, setSession] = React.useState(
    (typeof window !== 'undefined' && window.bsSession) || { authenticated: false, account: null }
  );
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);

  React.useEffect(() => {
    const handler = (e) => setSession(e.detail || { authenticated: false, account: null });
    document.addEventListener('bs:session-changed', handler);
    // Refrescar al montar
    if (typeof window.bsRefreshSession === 'function') {
      window.bsRefreshSession().then((s) => setSession(s)).catch(() => {});
    }
    return () => document.removeEventListener('bs:session-changed', handler);
  }, []);

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

  if (!session.authenticated) {
    return (
      <button
        onClick={() => window.bsOpenAuth && window.bsOpenAuth()}
        className="bs-btn bs-btn-acid bs-btn-sm"
        style={{ height: 36, fontSize: 13 }}
      >
        Empezar →
      </button>
    );
  }

  const account = session.account || {};
  const displayName = account.name || account.username || account.email || 'Usuario';
  const initial = (displayName.match(/\S/) || ['U'])[0].toUpperCase();

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button
        type="button"
        className="bs-avatar-btn"
        onClick={() => setOpen((o) => !o)}
        aria-haspopup="menu"
        aria-expanded={open}
        title={displayName}
      >
        <span className="bs-avatar">{initial}</span>
        <span className="bs-avatar-name">{displayName}</span>
        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: 0.6 }}>
          <path d="M6 9l6 6 6-6" />
        </svg>
      </button>
      {open && (
        <div className="bs-dropdown" role="menu">
          <div className="bs-dropdown-header">
            <div className="bs-avatar lg">{initial}</div>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--fg)', textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap' }}>{displayName}</div>
              {account.email ? <div style={{ fontSize: 11, color: 'var(--fg-3)', textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap' }}>{account.email}</div> : null}
            </div>
          </div>
          <a href="https://clientes.blackstock.es/perfil/" className="bs-dropdown-item" role="menuitem">
            <span>Portal de clientes</span>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17 17 7 M9 7h8v8" /></svg>
          </a>
          <a href="https://panel.blackstock.es/" className="bs-dropdown-item" role="menuitem">
            <span>Panel de operaciones</span>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17 17 7 M9 7h8v8" /></svg>
          </a>
          <a href="https://academia.blackstock.es/" className="bs-dropdown-item" role="menuitem">
            <span>Academia</span>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17 17 7 M9 7h8v8" /></svg>
          </a>
          <div className="bs-dropdown-divider" />
          <button
            type="button"
            className="bs-dropdown-item bs-dropdown-danger"
            role="menuitem"
            onClick={async () => {
              setOpen(false);
              if (typeof window.bsLogout === 'function') await window.bsLogout();
            }}
          >
            Cerrar sesión
          </button>
        </div>
      )}
    </div>
  );
};
window.UserAuthZone = UserAuthZone;

const Footer = () => (
  <footer style={{
    borderTop: '1px solid var(--line)',
    padding: '64px 0 40px',
    background: 'var(--bg)',
  }}>
    <div className="bs-container">
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr 1fr', gap: 48, marginBottom: 64 }}>
        <div>
          <Logo />
          <p style={{ marginTop: 16, color: 'var(--fg-3)', fontSize: 14, maxWidth: 280 }}>
            La capa operativa para revender en Vinted con IA, automatización y datos reales del mercado.
          </p>
          <div style={{ marginTop: 20, display: 'flex', gap: 8 }}>
            <span className="bs-pill"><span className="bs-dot live"></span>+30 resellers activos</span>
          </div>
        </div>
        {[
          {
            title: 'Producto',
            items: [
              { label: 'Sistema', href: '#' },
              { label: 'Bot de mercado', href: '#' },
              { label: 'Automatizaciones', href: '#' },
              { label: 'Multicuenta', href: '#' },
              { label: 'IA', href: '#' },
            ],
          },
          {
            title: 'Recursos',
            items: [
              { label: 'Academia', href: 'https://academia.blackstock.es/' },
              { label: 'Documentación', href: 'https://panel.blackstock.es/documentacion' },
              { label: 'Guías', href: 'https://panel.blackstock.es/guias' },
              { label: 'Extensión', href: '/legal/extension' },
              { label: 'Estado', href: '#' },
            ],
          },
          {
            title: 'Empresa',
            items: [
              { label: 'Sobre', href: '#' },
              { label: 'Casos', href: '#' },
              { label: 'Blog', href: '#' },
              { label: 'Contacto', href: 'mailto:hola@blackstock.es' },
            ],
          },
          {
            title: 'Legal',
            items: [
              { label: 'Términos', href: '/legal/terms' },
              { label: 'Privacidad', href: '/legal/privacy' },
              { label: 'Cookies', href: '/legal/cookies' },
              { label: 'Reembolsos', href: '/legal/refund' },
              { label: 'Descargo', href: '/legal/disclaimer' },
              { label: 'Uso aceptable', href: '/legal/acceptable-use' },
              { label: 'Extensión', href: '/legal/extension' },
            ],
          },
        ].map((col, i) => (
          <div key={i}>
            <div className="bs-eyebrow" style={{ marginBottom: 16 }}>{col.title}</div>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
              {col.items.map((it, j) => {
                const isPlaceholder = it.href === '#';
                return (
                  <li key={j}>
                    <a
                      href={it.href}
                      onClick={isPlaceholder ? (e) => e.preventDefault() : undefined}
                      style={{ color: 'var(--fg-2)', textDecoration: 'none', fontSize: 14 }}
                    >
                      {it.label}
                    </a>
                  </li>
                );
              })}
            </ul>
          </div>
        ))}
      </div>

      <div className="bs-divider"></div>

      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        paddingTop: 24, color: 'var(--fg-3)', fontSize: 12, fontFamily: 'var(--font-mono)',
      }}>
        <div>© 2026 BLACKSTOCK SYSTEMS · MADRID, ES</div>
        <div style={{ display: 'flex', gap: 24 }}>
          <span>STATUS: <span style={{ color: 'var(--ok)' }}>● OPERATIVO</span></span>
          <span>UPTIME: 99.98%</span>
          <span>LATENCY: 84ms</span>
        </div>
      </div>
    </div>
  </footer>
);

/* Sparkline */
const Sparkline = ({ width = 280, height = 60, points = null, smooth = true, color = 'var(--acid)' }) => {
  const data = points || [12, 18, 14, 22, 19, 28, 24, 32, 29, 38, 34, 42, 38, 48, 44, 52, 49, 58];
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const stepX = width / (data.length - 1);
  const pts = data.map((v, i) => [i * stepX, height - ((v - min) / range) * (height - 8) - 4]);
  const d = smooth
    ? pts.reduce((acc, [x, y], i) => {
        if (i === 0) return `M${x},${y}`;
        const [px, py] = pts[i - 1];
        const cx = (px + x) / 2;
        return `${acc} Q${px},${py} ${cx},${(py + y) / 2} T${x},${y}`;
      }, '')
    : 'M' + pts.map(p => p.join(',')).join(' L');
  const area = d + ` L${width},${height} L0,${height} Z`;
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} style={{ display: 'block' }}>
      <defs>
        <linearGradient id="sparkGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.25" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill="url(#sparkGrad)" />
      <path d={d} fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
};

/* Metric tile (used in panel mockups) */
const MetricTile = ({ label, value, sub, color = 'fg', size = 'md' }) => (
  <div style={{
    background: 'var(--bg-2)',
    border: '1px solid var(--line)',
    borderRadius: 12,
    padding: size === 'sm' ? '12px 14px' : '16px 18px',
    display: 'flex', flexDirection: 'column', gap: 6,
  }}>
    <div className="bs-eyebrow" style={{ fontSize: 10 }}>{label}</div>
    <div className="bs-num" style={{
      fontSize: size === 'sm' ? 22 : 28, fontWeight: 700,
      color: color === 'acid' ? 'var(--acid)' : 'var(--fg)',
      letterSpacing: '-0.025em', lineHeight: 1,
    }}>{value}</div>
    {sub && <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>{sub}</div>}
  </div>
);

/* Panel preview — used in hero A and product page */
const PanelPreview = ({ compact = false }) => {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 2200);
    return () => clearInterval(id);
  }, []);

  const ticker = ['Carhartt Detroit M · 92€', 'Acne scarf wool · 78€', 'Birkenstock Boston 42 · 65€', 'Levi\'s 501 MIUSA · 54€'];

  return (
    <div style={{
      background: 'linear-gradient(180deg, var(--bg-2), var(--bg-1))',
      border: '1px solid var(--line-2)',
      borderRadius: 16,
      padding: 22,
      boxShadow: '0 40px 80px -30px rgba(0,0,0,0.7), 0 0 0 1px rgba(214,255,77,0.04)',
      width: '100%',
      position: 'relative',
      overflow: 'hidden',
    }}>
      {/* Inner glow */}
      <div style={{
        position: 'absolute', top: -100, right: -80, width: 260, height: 260, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(214,255,77,0.10), transparent 60%)',
        pointerEvents: 'none',
      }} />

      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div className="bs-eyebrow" style={{ fontSize: 10 }}>HQ DE VENTAS</div>
        </div>
        <div className="bs-pill acid"><span className="bs-dot live"></span>LIVE</div>
      </div>

      <div style={{ marginBottom: 18 }}>
        <div className="bs-display" style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em' }}>
          La capa operativa
        </div>
        <div style={{ color: 'var(--fg-3)', fontSize: 13, marginTop: 4 }}>
          Pedidos, mensajes, restocks, IA — todo en un panel.
        </div>
      </div>

      {/* Top metrics */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, marginBottom: 12 }}>
        <MetricTile size="sm" label="HOY" value="4" sub="pedidos" />
        <MetricTile size="sm" label="TICKET" value="68€" sub="medio" />
        <MetricTile size="sm" label="X ENVIAR" value="2" sub="urgentes" color="acid" />
        <MetricTile size="sm" label="RESTOCKS" value="6" sub="publicados" />
      </div>

      {/* Chart */}
      <div style={{
        background: 'var(--bg-2)', border: '1px solid var(--line)',
        borderRadius: 12, padding: 14, marginBottom: 10,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
          <div>
            <div className="bs-eyebrow" style={{ fontSize: 10 }}>FACTURACIÓN HOY</div>
            <div className="bs-num" style={{ fontSize: 28, fontWeight: 700, color: 'var(--acid)', letterSpacing: '-0.03em' }}>
              268€
            </div>
          </div>
          <div className="bs-pill acid" style={{ fontSize: 10, height: 22 }}>+9% vs ayer</div>
        </div>
        <Sparkline width={compact ? 280 : 360} height={56} />
        <div style={{
          display: 'flex', justifyContent: 'space-between',
          fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-4)', marginTop: 6,
        }}>
          <span>00H</span><span>06H</span><span>12H</span><span>18H</span><span>NOW</span>
        </div>
      </div>

      {/* Activity ticker */}
      <div style={{
        background: 'var(--bg-2)', border: '1px solid var(--line)',
        borderRadius: 12, padding: 12,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <div style={{
          width: 8, height: 8, borderRadius: '50%', background: 'var(--ok)',
          boxShadow: '0 0 8px var(--ok)',
        }} />
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)' }}>VENDIDO</div>
        <div key={tick} style={{
          fontSize: 13, fontWeight: 500, color: 'var(--fg)',
          animation: 'bsFadeIn 400ms ease',
        }}>
          {ticker[tick % ticker.length]}
        </div>
        <div style={{ marginLeft: 'auto', fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-4)' }}>
          hace {Math.floor(Math.random() * 30) + 1}s
        </div>
      </div>
    </div>
  );
};

/* Floating chip for hero */
const FloatingChip = ({ label, value, sub, x, y, delay = 0 }) => (
  <div style={{
    position: 'absolute', left: x, top: y,
    background: 'rgba(22, 23, 14, 0.92)',
    border: '1px solid var(--line-2)',
    borderRadius: 12,
    padding: '10px 14px',
    display: 'flex', flexDirection: 'column', gap: 2,
    backdropFilter: 'blur(10px)',
    boxShadow: '0 12px 32px -8px rgba(0,0,0,0.6)',
    animation: `bsFloat 4s ease-in-out ${delay}s infinite`,
  }}>
    <div className="bs-eyebrow" style={{ fontSize: 9 }}>{label}</div>
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
      <span className="bs-num" style={{ fontSize: 18, fontWeight: 700, color: 'var(--acid)' }}>{value}</span>
      {sub && <span style={{ fontSize: 11, color: 'var(--fg-3)' }}>{sub}</span>}
    </div>
  </div>
);

Object.assign(window, {
  LogoMark, Logo, Nav, Footer, Sparkline, MetricTile, PanelPreview, FloatingChip,
});
