// mockups/home-pills.jsx — Home dashboard fiel al producto real.
//
// Layout (1280×720):
//   - Greeting al top: fecha (mono small) + "Buenas tardes, Amelia" + subtítulo
//   - 4 cards de módulos activos en una fila (blancas, icon tile tinted, stats abajo)
//   - 10 pills de texto al bottom, 1 sola fila, sin label
//
// Props:
//   greetingProgress   : 0..1
//   pillsProgress      : 0..1 (stagger interno)
//   activatedModules   : array of module keys already landed
//   activationProgress : 0..1 of current activating module
//
// Exports: HomePills, MODULES_ALL, MODULES_ACTIVE, MODULE_META

// ── Module catalog with full metadata for cards + pills ──────────────
const MODULE_META = {
  taxes:       { label: 'Taxes',        color: '#007AFF', bgTile: '#dbeafe', descr: 'Preparación fiscal. Formularios 1040, Schedule A, C, E y todos los 1099.', stats: [['Clientes activos', 4], ['En progreso', 4]] },
  migracion:   { label: 'Migración',    color: '#FF9500', bgTile: '#ffedd5', descr: 'Formas USCIS. I-130, I-485, I-765, N-400 y mociones EOIR.',                stats: [['Clientes activos', 10], ['En progreso', 10]] },
  credit:      { label: 'Credit Repair',color: '#FF3B30', bgTile: '#fee2e2', descr: 'Limpieza y monitoreo de crédito. Disputas y seguimiento.',                 stats: [['Clientes activos', 6],  ['En progreso', 3]] },
  insurance:   { label: 'Insurance',    color: '#5AC8FA', bgTile: '#dbeafe', descr: 'Cotización y pólizas. Salud, vida, auto.',                                  stats: [['Clientes activos', 0],  ['En progreso', 0]] },
  legal:       { label: 'Legal',        color: '#5856D6', bgTile: '#e0e7ff', descr: 'Consultas y casos legales para clientes del office.',                       stats: [['Clientes activos', 0],  ['En progreso', 0]] },
  explain:     { label: 'Explain',      color: '#8b5cf6', bgTile: '#f3e8ff', descr: 'Sophia traduce notices del USCIS, IRS y cartas legales del cliente.',     stats: [['Clientes activos', 12], ['En progreso', 5]] },
  event:       { label: 'Event Hub',    color: '#FF2D55', bgTile: '#fce7f3', descr: 'Webinars y eventos del office.',                                            stats: [['Clientes activos', 0],  ['En progreso', 0]] },
  business:    { label: 'Business',     color: '#FF9500', bgTile: '#ffedd5', descr: 'Formación de LLC, EIN y cumplimiento del negocio.',                         stats: [['Clientes activos', 0],  ['En progreso', 0]] },
  marketplace: { label: 'Marketplace',  color: '#6e6e73', bgTile: '#e8e8ed', descr: 'Productos y servicios para office.',                                        stats: [['Clientes activos', 0],  ['En progreso', 0]] },
  partner:     { label: 'Partner Portal', color: '#1d1d1f', bgTile: '#e8e8ed', descr: 'Portal de socios y referidos.',                                          stats: [['Clientes activos', 0],  ['En progreso', 0]] },
};

const MODULES_ALL = ['taxes','migracion','credit','insurance','legal','explain','event','business','marketplace','partner'];
const MODULES_ACTIVE = ['taxes', 'migracion', 'credit', 'explain'];

// ── SVG icons (clean, stroke-based) ──────────────────────────────────
function ModuleIcon({ moduleKey, color = '#1d1d1f', size = 22 }) {
  const props = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: color, strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round' };
  if (moduleKey === 'taxes') {
    return (
      <svg {...props}>
        <rect x="5" y="3" width="14" height="18" rx="2.5" />
        <line x1="8" y1="7" x2="16" y2="7" />
        <line x1="8.5" y1="11" x2="9.5" y2="11" />
        <line x1="11.5" y1="11" x2="12.5" y2="11" />
        <line x1="14.5" y1="11" x2="15.5" y2="11" />
        <line x1="8.5" y1="14.5" x2="9.5" y2="14.5" />
        <line x1="11.5" y1="14.5" x2="12.5" y2="14.5" />
        <line x1="14.5" y1="14.5" x2="15.5" y2="14.5" />
        <line x1="8.5" y1="18" x2="9.5" y2="18" />
        <line x1="11.5" y1="18" x2="12.5" y2="18" />
        <line x1="14.5" y1="18" x2="15.5" y2="18" />
      </svg>
    );
  }
  if (moduleKey === 'migracion') {
    return (
      <svg {...props}>
        <rect x="3" y="5" width="18" height="14" rx="2.5" />
        <circle cx="9" cy="11" r="2" />
        <path d="M5.5 17c0.5-1.7 2.2-2.6 3.5-2.6s3 0.9 3.5 2.6" />
        <line x1="14.5" y1="10" x2="18.5" y2="10" />
        <line x1="14.5" y1="13" x2="17.5" y2="13" />
      </svg>
    );
  }
  if (moduleKey === 'credit') {
    return (
      <svg {...props} strokeWidth={2}>
        <polyline points="4 17 9 12 13 16 20 8" />
        <polyline points="14 8 20 8 20 14" />
      </svg>
    );
  }
  if (moduleKey === 'insurance') {
    return (
      <svg {...props}>
        <path d="M12 3l8 3v6c0 4.5-3.5 8-8 9-4.5-1-8-4.5-8-9V6l8-3z" />
        <path d="M9 12l2 2 4-4" />
      </svg>
    );
  }
  if (moduleKey === 'legal') {
    return (
      <svg {...props}>
        <line x1="12" y1="4" x2="12" y2="20" />
        <path d="M6 8l-3 5c0 1.7 1.3 3 3 3s3-1.3 3-3l-3-5z" />
        <path d="M18 8l-3 5c0 1.7 1.3 3 3 3s3-1.3 3-3l-3-5z" />
        <line x1="5" y1="20" x2="19" y2="20" />
        <line x1="9" y1="6" x2="15" y2="6" />
      </svg>
    );
  }
  if (moduleKey === 'explain') {
    return (
      <svg {...props}>
        <path d="M12 2C7 2 5 5 5 8c0 2.5 1.5 4.5 4 5.5V17h6v-3.5c2.5-1 4-3 4-5.5 0-3-2-6-7-6z" />
        <line x1="9" y1="19" x2="15" y2="19" />
        <line x1="10" y1="21" x2="14" y2="21" />
      </svg>
    );
  }
  if (moduleKey === 'event') {
    return (
      <svg {...props}>
        <rect x="4" y="5" width="16" height="15" rx="2" />
        <line x1="4" y1="10" x2="20" y2="10" />
        <line x1="9" y1="3" x2="9" y2="7" />
        <line x1="15" y1="3" x2="15" y2="7" />
      </svg>
    );
  }
  if (moduleKey === 'business') {
    return (
      <svg {...props}>
        <rect x="4" y="7" width="16" height="13" rx="1.5" />
        <path d="M9 7V5a2 2 0 012-2h2a2 2 0 012 2v2" />
        <line x1="4" y1="13" x2="20" y2="13" />
      </svg>
    );
  }
  if (moduleKey === 'marketplace') {
    return (
      <svg {...props}>
        <path d="M4 9l1-4h14l1 4M4 9v10h16V9M4 9h16" />
        <path d="M9 13a3 3 0 006 0" />
      </svg>
    );
  }
  if (moduleKey === 'partner') {
    return (
      <svg {...props}>
        <path d="M8 12l-3 4 2 1 4-4M16 12l3 4-2 1-4-4" />
        <path d="M9 8l3-3 3 3" />
        <circle cx="12" cy="11" r="2" />
      </svg>
    );
  }
  return null;
}

// ── Main HomePills component ─────────────────────────────────────────
function HomePills({
  greetingProgress = 1,
  pillsProgress = 1,
  moduleProgresses = [0, 0, 0, 0],
  userName = 'Amelia',
}) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const h = i18n.home || {};
  // Card row layout
  const CARDS_TOP = 220;
  const CARD_W = 218;
  const CARD_H = 244;
  const CARD_GAP = 16;
  const TOTAL_CARDS_W = CARD_W * 4 + CARD_GAP * 3;
  // Center across full canvas (iPhone is hidden during Act 1)
  const CARDS_LEFT = (1280 - TOTAL_CARDS_W) / 2;

  // Pill row layout (single horizontal row)
  const PILL_TOP = 580;
  const PILL_H = 32;
  const PILL_PADDING = 14;

  function cardPos(slot) {
    return {
      left: CARDS_LEFT + slot * (CARD_W + CARD_GAP),
      top: CARDS_TOP,
    };
  }

  // Per-module independent progress (no reset when next module starts)
  const activeCards = MODULES_ACTIVE.map((mk, slot) => {
    const progress = moduleProgresses[slot] || 0;
    return { moduleKey: mk, slot, progress, pos: cardPos(slot) };
  });

  // Today's date (matches the system date in the brief)
  const todayLabel = h.date_label || 'SÁBADO, 16 DE MAYO';

  return (
    <div style={{
      position: 'absolute',
      inset: 0,
      background: '#f5f5f7',
      overflow: 'hidden',
    }}>
      <AppHeader />

      {/* ── Greeting ────────────────────────────────────────────── */}
      <div style={{
        position: 'absolute',
        top: 80,
        left: 0,
        width: 1280, // full canvas (iPhone hidden in Act 1)
        textAlign: 'center',
        opacity: greetingProgress,
        transform: `translateY(${(1 - greetingProgress) * 10}px)`,
        transition: 'opacity 240ms, transform 240ms',
      }}>
        <div style={{
          fontFamily: 'ui-monospace, "SF Mono", monospace',
          fontSize: 10.5,
          fontWeight: 600,
          letterSpacing: 0.16,
          textTransform: 'uppercase',
          color: '#a1a1a6',
          marginBottom: 10,
        }}>{todayLabel}</div>
        <div style={{
          fontSize: 36,
          fontWeight: 600,
          letterSpacing: -0.025,
          color: '#1d1d1f',
          marginBottom: 6,
          lineHeight: 1.1,
        }}>{h.greeting || 'Buenas tardes,'} {userName}</div>
        <div style={{
          fontSize: 14,
          color: '#6e6e73',
          letterSpacing: -0.005,
        }}>{h.sub_question || '¿En qué vas a trabajar hoy?'}</div>
      </div>

      {/* ── Active module cards ─────────────────────────────────── */}
      {activeCards.map(({ moduleKey, slot, progress, pos }) => {
        if (progress <= 0) return null;
        return (
          <ModuleCard
            key={moduleKey}
            moduleKey={moduleKey}
            progress={progress}
            x={pos.left}
            y={pos.top}
            w={CARD_W}
            h={CARD_H}
          />
        );
      })}

      {/* ── Pills row (single horizontal row, text-only) ───────── */}
      <PillRow
        progress={pillsProgress}
        top={PILL_TOP}
        height={PILL_H}
      />
    </div>
  );
}

// ── Module Card (white, with icon tile + stats + subtle accent border) ─
function ModuleCard({ moduleKey, progress, x, y, w, h }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const hm = i18n.home || {};
  const meta = MODULE_META[moduleKey];
  if (!meta) return null;

  // Entry animation: card rises up + fades in + slight scale
  const e = Easing.easeOutCubic(progress);
  const ty = (1 - e) * 56;
  const opacity = Math.min(1, progress * 1.4);
  const scale = 0.92 + 0.08 * e;

  // Border: colored accent that GROWS IN with the card — no flash, no flip.
  // Parse meta.color to rgba so we can ramp alpha smoothly from 0 → 0.45.
  const _r = parseInt(meta.color.slice(1,3), 16);
  const _g = parseInt(meta.color.slice(3,5), 16);
  const _b = parseInt(meta.color.slice(5,7), 16);
  // Mix with subtle gray so empty slot doesn't have an invisible border
  const borderAlpha = 0.10 + 0.38 * e;
  const borderRgba = `rgba(${_r}, ${_g}, ${_b}, ${borderAlpha})`;

  return (
    <div style={{
      position: 'absolute',
      left: x,
      top: y,
      width: w,
      height: h,
      background: '#fff',
      borderRadius: 16,
      border: `1px solid ${borderRgba}`,
      // Single soft depth shadow that grows with the card (no separate pulse layer)
      boxShadow: `0 ${2 + 14 * e}px ${10 + 24 * e}px rgba(0, 0, 0, ${0.04 + 0.04 * e})`,
      opacity,
      transform: `translateY(${ty}px) scale(${scale})`,
      padding: '18px 18px 16px',
      display: 'flex',
      flexDirection: 'column',
      willChange: 'transform, opacity',
      transition: 'border-color 320ms',
    }}>
      {/* Top row: icon tile + arrow */}
      <div style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'flex-start',
        marginBottom: 18,
      }}>
        <div style={{
          width: 44, height: 44,
          borderRadius: 11,
          background: meta.bgTile,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          color: meta.color,
        }}>
          <ModuleIcon moduleKey={moduleKey} color={meta.color} size={22} />
        </div>
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" style={{ marginTop: 6 }}>
          <path d="M5 3l5 5-5 5" stroke="#a1a1a6" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </div>

      {/* Title */}
      <div style={{
        fontSize: 19,
        fontWeight: 600,
        letterSpacing: -0.015,
        color: '#1d1d1f',
        marginBottom: 8,
      }}>{(i18n.modules && i18n.modules[moduleKey]) || meta.label}</div>

      {/* Description */}
      <div style={{
        fontSize: 12,
        color: '#6e6e73',
        letterSpacing: -0.005,
        lineHeight: 1.45,
        marginBottom: 'auto',
      }}>{hm[meta.descKey] || meta.descr}</div>

      {/* Divider */}
      <div style={{
        height: 1,
        background: '#f0f0f3',
        margin: '14px 0 10px',
      }} />

      {/* Stats */}
      {meta.stats.map(([label, val]) => (
        <div key={(label === 'active' ? (hm.stat_active || 'Clientes activos') : label === 'progress' ? (hm.stat_progress || 'En progreso') : label)} style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          fontSize: 12,
          padding: '2px 0',
        }}>
          <span style={{ color: '#6e6e73' }}>{(label === 'active' ? (hm.stat_active || 'Clientes activos') : label === 'progress' ? (hm.stat_progress || 'En progreso') : label)}</span>
          <span style={{ color: '#1d1d1f', fontWeight: 600 }}>{val}</span>
        </div>
      ))}
    </div>
  );
}

// ── Pill row ─────────────────────────────────────────────────────────
function PillRow({ progress, top, height }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  // Stagger pills appearing left-to-right based on progress
  return (
    <div style={{
      position: 'absolute',
      top,
      left: 0,
      width: 1280, // full canvas (iPhone hidden in Act 1)
      display: 'flex',
      justifyContent: 'center',
      gap: 8,
    }}>
      {MODULES_ALL.map((mk, i) => {
        const order = i;
        const myAppear = Math.max(0, Math.min(1, (progress * 12 - order) / 2));
        if (myAppear <= 0) return null;
        const meta = MODULE_META[mk];
        return (
          <div key={mk} style={{
            background: '#fff',
            border: '1px solid #e8e8ed',
            borderRadius: 999,
            padding: '0 14px',
            height,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: 12,
            fontWeight: 500,
            color: '#1d1d1f',
            letterSpacing: -0.005,
            opacity: 0.5 + 0.5 * myAppear,
            transform: `translateY(${(1 - myAppear) * 8}px)`,
            transition: 'opacity 200ms, transform 200ms',
            whiteSpace: 'nowrap',
            boxShadow: '0 1px 2px rgba(0,0,0,0.02)',
          }}>{(i18n.modules && i18n.modules[mk]) || meta.label}</div>
        );
      })}
    </div>
  );
}

Object.assign(window, { HomePills, MODULES_ALL, MODULES_ACTIVE, MODULE_META, ModuleIcon });
