/* ═══════════════════════════════════════════════════════
   IKIGAI · Discovery Cockpit · Fase A1
   Dataset local + resolver de intención + categorías + tarjetas glass
   (Sin backend: matching local por categoría/keywords con razones visibles)
   ═══════════════════════════════════════════════════════ */

const { useState: useState_dc, useRef: useRef_dc } = React;

// ───────────── Dataset local de clientes IKIGAI ─────────────
// Solo datos públicos. Nada de números/contactos inventados (R1).
const DISCOVERY_CLIENTS = [
  {
    id: 'qruzh',
    brand: 'Qruzh',
    glyph: 'Q',
    color: '#6EA8FF',
    categoryKey: 'accesorios',
    categoryLabel: 'Accesorios para celular',
    keywords: ['cargador', 'funda', 'iphone', 'celular', 'apple', 'airpods', 'accesorio',
               'telefono', 'movil', 'cable', 'audifonos', 'protector', 'mica', 'case'],
    url: 'https://qruzh.com.mx',
    urlLabel: 'qruzh.com.mx',
    location: 'Cancún · Nacional',
    priceLevel: '$$',
    rating: null,
    tagline: 'Accesorios Apple originales · iPhone · AirPods',
    premium: true,
    cta: { label: 'Ver tienda', href: 'https://qruzh.com.mx' },
  },
  {
    id: 'torreland',
    brand: 'Torre Land',
    glyph: 'T',
    color: '#7EF6E2',
    categoryKey: 'construccion',
    categoryLabel: 'Construcción y mantenimiento',
    keywords: ['alberca', 'mantenimiento', 'construccion', 'obra', 'remodelacion', 'piscina',
               'domus', 'casa', 'reparacion', 'cancun', 'pool'],
    url: 'https://torreland.com.mx',
    urlLabel: 'torreland.com.mx',
    location: 'Cancún, QR',
    priceLevel: '$$$',
    rating: null,
    tagline: 'Construcción · Mantenimiento · Cancún',
    premium: false,
    cta: { label: 'Ver página', href: 'https://torreland.com.mx' },
  },
  {
    id: 'maison',
    brand: 'Maison Solune',
    glyph: 'S',
    color: '#F5DFA7',
    categoryKey: 'perfumeria',
    categoryLabel: 'Perfumería',
    keywords: ['perfume', 'fragancia', 'perfumeria', 'aroma', 'esencia', 'artesanal', 'olor'],
    url: 'https://maisonsolune.com.mx',
    urlLabel: 'maisonsolune.com.mx',
    location: 'México',
    priceLevel: '$$$',
    rating: null,
    tagline: 'Perfumería artesanal · Storytelling sensorial',
    premium: false,
    cta: { label: 'Ver página', href: 'https://maisonsolune.com.mx' },
  },
  {
    id: 'vault',
    brand: 'IKIGAI Personal Vault',
    glyph: 'V',
    color: '#9B8CFF',
    categoryKey: 'vaults',
    categoryLabel: 'Vaults',
    keywords: ['vault', 'memoria', 'organizar', 'vida', 'documentos', 'proposito', 'orden', 'recuerdos'],
    url: 'https://vault.qruzh.com.mx',
    urlLabel: 'vault.qruzh.com.mx',
    location: 'Privado',
    priceLevel: null,
    rating: null,
    tagline: 'Tu memoria. Tus documentos. Tu propósito.',
    premium: false,
    cta: { label: 'Entrar', href: 'https://vault.qruzh.com.mx' },
  },
];

// Categorías del header. Las que aún no tienen cliente quedan como `soon` (honestidad: R1).
const DISCOVERY_CATEGORIES = [
  { key: 'accesorios',   label: 'Accesorios' },
  { key: 'perfumeria',   label: 'Perfumería' },
  { key: 'construccion', label: 'Construcción' },
  { key: 'vaults',       label: 'Vaults' },
  { key: 'ropa',         label: 'Ropa',    soon: true },
  { key: 'zapatos',      label: 'Zapatos', soon: true },
  { key: 'bolsas',       label: 'Bolsas',  soon: true },
];

function normalize_dc(s) {
  return (s || '')
    .normalize('NFD')
    .replace(new RegExp('[\\u0300-\\u036f]', 'g'), '')
    .toLowerCase();
}

// ───────────── Resolver local (ranking explicable) ─────────────
// Devuelve [{ client, reason, premium }] ordenado, máx 5.
// Nunca incluye un cliente premium si no hay relevancia real (regla 4/5 v3).
function resolveDiscovery(query, categoryKey) {
  const q = normalize_dc(query);
  const tokens = q.split(/[^a-z0-9]+/).filter(Boolean);

  const scored = DISCOVERY_CLIENTS.map((client) => {
    let score = 0;
    const hits = [];

    if (categoryKey && client.categoryKey === categoryKey) {
      score += 10;
      hits.push(client.categoryLabel.toLowerCase());
    }

    for (const kw of client.keywords) {
      const nkw = normalize_dc(kw);
      if (!nkw) continue;
      if (q.includes(nkw) || tokens.includes(nkw)) {
        score += 3;
        if (hits.length < 3) hits.push(kw);
      }
    }

    // Boost premium SOLO si ya hay relevancia (nunca en búsquedas irrelevantes).
    if (score > 0 && client.premium) score += 1;

    return { client, score, hits };
  });

  return scored
    .filter((s) => s.score > 0)
    .sort((a, b) => b.score - a.score)
    .slice(0, 5)
    .map((s) => ({
      client: s.client,
      premium: s.client.premium,
      reason: buildReason_dc(s.client, s.hits),
    }));
}

function buildReason_dc(client, hits) {
  const unique = [...new Set(hits)];
  if (!unique.length) return `Coincide con ${client.categoryLabel.toLowerCase()}.`;
  return `Aparece porque coincide con ${unique.slice(0, 3).join(' · ')}.`;
}

// ───────────── Header de categorías (chips) ─────────────
function HeaderCategories({ active }) {
  return (
    <div className="cat-bar" role="navigation" aria-label="Categorías IKIGAI">
      {DISCOVERY_CATEGORIES.map((c) => (
        <button
          key={c.key}
          type="button"
          className={`cat-chip ${c.soon ? 'cat-chip--soon' : ''} ${active === c.key ? 'is-active' : ''}`}
          aria-pressed={active === c.key}
          onClick={() => {
            window.dispatchEvent(new CustomEvent('ikigai:category', {
              detail: { key: c.key, label: c.label, soon: !!c.soon },
            }));
          }}
        >
          {c.label}
          {c.soon && <span className="cat-chip__soon">pronto</span>}
        </button>
      ))}
    </div>
  );
}

// ───────────── Tarjeta de cliente (glass + 3D tilt) ─────────────
function IkigaiClientCard({ data, reason, premium, dimmed }) {
  const ref = useRef_dc(null);

  function onMove(e) {
    const el = ref.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    const px = (e.clientX - r.left) / r.width;   // 0..1
    const py = (e.clientY - r.top) / r.height;   // 0..1
    const ry = (px - 0.5) * 12;                  // máx ±6°
    const rx = (0.5 - py) * 12;
    el.style.setProperty('--rx', rx.toFixed(2) + 'deg');
    el.style.setProperty('--ry', ry.toFixed(2) + 'deg');
    el.style.setProperty('--mx', (px * 100).toFixed(1) + '%');
    el.style.setProperty('--my', (py * 100).toFixed(1) + '%');
  }
  function onLeave() {
    const el = ref.current;
    if (!el) return;
    el.style.setProperty('--rx', '0deg');
    el.style.setProperty('--ry', '0deg');
  }

  return (
    <a
      ref={ref}
      href={data.cta?.href || data.url}
      target="_blank"
      rel="noopener noreferrer"
      className={`dcard ${dimmed ? 'is-dimmed' : ''} ${premium ? 'dcard--premium' : ''}`}
      style={{ '--accent': data.color }}
      onMouseMove={onMove}
      onMouseLeave={onLeave}
    >
      <div className="dcard__sheen" />
      {premium && <span className="dcard__badge">Destacado</span>}
      <div className="dcard__head">
        <span className="dcard__glyph" aria-hidden="true">{data.glyph}</span>
        <span className="dcard__cat">{data.categoryLabel}</span>
      </div>
      <div className="dcard__name">{data.brand}</div>
      <div className="dcard__tag">{data.tagline}</div>
      {reason && <div className="dcard__reason">{reason}</div>}
      <div className="dcard__meta">
        {data.location && <span>{data.location}</span>}
        {data.priceLevel && <span>{data.priceLevel}</span>}
        {data.rating ? <span>★ {data.rating}</span> : null}
      </div>
      <div className="dcard__cta">
        <span>{data.cta?.label || 'Ver página'}</span>
        <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true">
          <path d="M3 7h7M7 3l4 4-4 4" stroke="currentColor" strokeWidth="1.2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </div>
    </a>
  );
}

// ───────────── Zona de resultados (máx 5) ─────────────
function DiscoveryResults({ matches, dimmed }) {
  if (!matches || !matches.length) return null;
  return (
    <div className="discovery-grid" role="list">
      {matches.slice(0, 5).map((m) => (
        <div role="listitem" key={m.client.id}>
          <IkigaiClientCard
            data={m.client}
            reason={m.reason}
            premium={m.premium}
            dimmed={dimmed}
          />
        </div>
      ))}
    </div>
  );
}

window.DISCOVERY_CLIENTS = DISCOVERY_CLIENTS;
window.DISCOVERY_CATEGORIES = DISCOVERY_CATEGORIES;
window.resolveDiscovery = resolveDiscovery;
window.HeaderCategories = HeaderCategories;
window.IkigaiClientCard = IkigaiClientCard;
window.DiscoveryResults = DiscoveryResults;
