// mockups/dashboard-home.jsx — Taxes module dashboard
// Pantalla principal con sidebar + hero "Pregúntale a Sophia" + 4 stats + casos recientes + botón "+ Nuevo cliente"
//
// Props:
//   greetingProgress : 0..1   fade-in del hero
//   newClientHover   : bool   hover state on +Nuevo cliente button
//   newClientPressed : bool   button being clicked (brief)
//
// Exports: DashboardHome

const DASH_NAV = {
  principal: [
    { key: 'dashboard', labelKey: 'nav_dashboard', fallback: 'Dashboard', active: true },
    { key: 'nuevo',     labelKey: 'nav_nuevo',     fallback: 'Nuevo cliente' },
    { key: 'cal',       labelKey: 'nav_cal',       fallback: 'Calendario' },
  ],
  clientes: [
    { key: 'lista',     labelKey: 'nav_lista',     fallback: 'Lista de clientes' },
    { key: 'msgs',      labelKey: 'nav_msgs',      fallback: 'Mensajes' },
  ],
  reportes: [
    { key: 'excel',     labelKey: 'nav_excel',     fallback: '📊 Excel de casos' },
  ],
  cuenta: [
    { key: 'sub',       labelKey: 'nav_sub',       fallback: 'Mi suscripción' },
    { key: 'usuarios',  labelKey: 'nav_users',     fallback: 'Usuarios' },
    { key: 'config',    labelKey: 'nav_config',    fallback: 'Configuración' },
  ],
};

function DashboardHome({
  greetingProgress = 1,
  newClientHover = false,
  newClientPressed = false,
  injectedCase = null,    // { progress: 0..1 } — prepend TOMÁS row at top, push existing rows down
}) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const db = i18n.dashboard || {};
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: '#fafafa',
      overflow: 'hidden',
    }}>
      <AppHeader moduleName="Taxes" moduleAccent="#007AFF" moduleIcon="🧮" />
      <DashSidebar />

      {/* Main area */}
      <div style={{
        position: 'absolute',
        top: 54, left: 196, right: 0, bottom: 0,
        padding: '18px 28px',
        overflow: 'hidden',
      }}>
        <GreetingHero progress={greetingProgress} />
        <StatsRow />
        <CasosSection hover={newClientHover} pressed={newClientPressed} injectedCase={injectedCase} />
      </div>
    </div>
  );
}

// ── Sidebar ──────────────────────────────────────────────────────────
function DashSidebar() {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const db = i18n.dashboard || {};
  return (
    <div style={{
      position: 'absolute',
      top: 54, left: 0, bottom: 0,
      width: 196,
      background: '#fff',
      borderRight: '1px solid #e8e8ed',
      padding: '18px 0',
      fontSize: 12.5,
      overflow: 'hidden',
    }}>
      {Object.entries(DASH_NAV).map(([groupKey, items], gi) => (
        <div key={groupKey} style={{ marginBottom: 18 }}>
          <div style={{
            padding: '0 22px 6px',
            fontSize: 9.5,
            fontWeight: 600,
            color: '#a1a1a6',
            letterSpacing: 0.14,
            textTransform: 'uppercase',
          }}>{db['group_' + groupKey] || groupKey.toUpperCase()}</div>
          {items.map(it => (
            <div key={it.key} style={{
              padding: '6px 22px',
              display: 'flex',
              alignItems: 'center',
              gap: 8,
              fontSize: 12.5,
              color: it.active ? '#007AFF' : '#1d1d1f',
              fontWeight: it.active ? 500 : 400,
              background: it.active ? 'rgba(0,122,255,0.06)' : 'transparent',
              borderLeft: `2px solid ${it.active ? '#007AFF' : 'transparent'}`,
              marginLeft: -2,
              letterSpacing: -0.005,
              lineHeight: 1.4,
            }}>
              <span style={{
                width: 5, height: 5,
                borderRadius: '50%',
                background: it.active ? '#007AFF' : '#34C759',
                display: 'inline-block',
                flexShrink: 0,
              }} />
              {db[it.labelKey] || it.fallback || it.label}
            </div>
          ))}
        </div>
      ))}
    </div>
  );
}

// ── Greeting hero card ───────────────────────────────────────────────
function GreetingHero({ progress }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const db = i18n.dashboard || {};
  const dx = i18n.dashboard_extra || {};
  return (
    <div style={{
      position: 'relative',
      background: 'linear-gradient(110deg, #ede9fe 0%, #e0e7ff 50%, #dbeafe 100%)',
      border: '1px solid rgba(139, 92, 246, 0.18)',
      borderRadius: 16,
      padding: '18px 24px',
      display: 'flex',
      alignItems: 'center',
      gap: 18,
      opacity: progress,
      transform: `translateY(${(1 - progress) * 8}px)`,
      transition: 'opacity 240ms, transform 240ms',
      marginBottom: 14,
    }}>
      {/* Sophia gradient avatar */}
      <div style={{
        width: 56, height: 56,
        borderRadius: '50%',
        background: 'radial-gradient(circle at 35% 30%, #c4b5fd 0%, #8b5cf6 60%, #5b21b6 100%)',
        boxShadow: '0 4px 14px rgba(139, 92, 246, 0.35), 0 0 0 3px rgba(139, 92, 246, 0.15)',
        flexShrink: 0,
        position: 'relative',
        overflow: 'hidden',
      }}>
        <img
          src="../static/avatar_sophia/sophia_v1_outfit_01_neutra.jpg"
          alt="Sophia"
          style={{
            width: '100%', height: '100%',
            objectFit: 'cover',
            objectPosition: '50% 15%',
          }}
          onError={(e) => { e.target.style.display = 'none'; }}
        />
      </div>

      {/* Center text */}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 18,
          fontWeight: 600,
          color: '#1d1d1f',
          letterSpacing: -0.02,
          marginBottom: 4,
        }}>{db.greeting || 'Buenas tardes, Amelia.'}</div>
        <div style={{
          fontSize: 12.5,
          color: '#52525b',
          letterSpacing: -0.005,
          marginBottom: 10,
        }}>{dx.hero_sub || 'Todo al día — sin pendientes urgentes.'}</div>
        <div style={{
          display: 'inline-block',
          padding: '7px 18px',
          background: '#fff',
          borderRadius: 999,
          border: '1px solid rgba(139, 92, 246, 0.3)',
          fontSize: 13,
          fontFamily: '"Snell Roundhand", "Apple Chancery", cursive',
          fontStyle: 'italic',
          color: '#7c3aed',
          letterSpacing: 0.01,
          boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
        }}>{dx.ask_sophia || 'Pregúntale a Sophia'}</div>
      </div>

      {/* TAXES badge */}
      <div style={{
        padding: '4px 10px',
        border: '1px solid #007AFF',
        borderRadius: 6,
        color: '#007AFF',
        fontSize: 10.5,
        fontWeight: 600,
        letterSpacing: 0.04,
        alignSelf: 'flex-start',
      }}>TAXES</div>
    </div>
  );
}

// ── Stats row ────────────────────────────────────────────────────────
const STATS = [
  { key: 'totales',    labelKey: 'stat_totales_label',    label: 'CASOS TOTALES', value: '11',       subKey: 'stat_totales_sub',    sub: 'desde el inicio',     accent: '#007AFF' },
  { key: 'pendientes', labelKey: 'stat_pendientes_label', label: 'PENDIENTES',    value: '11',       subKey: 'stat_pendientes_sub', sub: 'en proceso',           accent: '#FF9500' },
  { key: 'comp',       labelKey: 'stat_comp_label',       label: 'COMPLETADOS',   value: '0',        subKey: 'stat_comp_sub',       sub: 'finalizados',          accent: '#34C759' },
  { key: 'plan',       labelKey: 'stat_plan_label',       label: 'PLAN ACTIVO',   valueKey: 'stat_plan_value', value: 'Empresa', subKey: 'stat_plan_sub', sub: 'suscripción activa', accent: '#5856D6', isPlan: true },
];

function StatsRow() {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const db = i18n.dashboard || {};
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: 'repeat(4, 1fr)',
      gap: 12,
      marginBottom: 14,
    }}>
      {STATS.map(s => (
        <div key={s.key} style={{
          background: '#fff',
          border: '1px solid #e8e8ed',
          borderLeft: `3px solid ${s.accent}`,
          borderRadius: 10,
          padding: '12px 14px',
        }}>
          <div style={{
            fontSize: 9.5,
            fontWeight: 600,
            color: '#a1a1a6',
            letterSpacing: 0.14,
            marginBottom: 6,
          }}>{db[s.labelKey] || s.label}</div>
          <div style={{
            fontSize: s.isPlan ? 18 : 26,
            fontWeight: 600,
            color: '#1d1d1f',
            letterSpacing: -0.02,
            lineHeight: 1,
            marginBottom: 5,
          }}>{db[s.valueKey] || s.value}</div>
          <div style={{
            fontSize: 10.5,
            color: '#6e6e73',
            letterSpacing: -0.005,
          }}>{db[s.subKey] || s.sub}</div>
        </div>
      ))}
    </div>
  );
}

// ── Casos section ────────────────────────────────────────────────────
const RECENT_CASOS = [
  { id: 'mp', cliente: 'maria perez',        ocupacion: '—', creado: 'Test Usuario', fecha: '2026-05-09', estadoKey: 'case_status_proceso', estado: 'En proceso' },
  { id: 'ym', cliente: 'YANET MEDINA ROMERO', ocupacion: '—', creado: 'Test Usuario', fecha: '2026-05-08', estadoKey: 'case_status_proceso', estado: 'En proceso' },
];

function CasosSection({ hover, pressed, injectedCase }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const db = i18n.dashboard || {};
  const injP = injectedCase ? Math.max(0, Math.min(1, injectedCase.progress || 0)) : 0;
  const injE = Easing.easeOutCubic(injP);
  const rowH = 46;
  const visibleHeight = rowH * injE;
  const showPulse = injP > 0 && injP < 1;
  return (
    <div>
      {/* Header row */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        gap: 16,
        marginBottom: 10,
      }}>
        <h3 style={{
          fontSize: 15,
          fontWeight: 600,
          color: '#1d1d1f',
          letterSpacing: -0.015,
          margin: 0,
        }}>{db.casos_title || 'Casos recientes'}</h3>

        {/* Search */}
        <div style={{
          flex: 1,
          maxWidth: 360,
          display: 'flex',
          alignItems: 'center',
          gap: 8,
          padding: '7px 14px',
          background: '#fff',
          border: '1px solid #e8e8ed',
          borderRadius: 999,
          fontSize: 12,
          color: '#a1a1a6',
        }}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <circle cx="11" cy="11" r="7"/><path d="M21 21l-4.35-4.35"/>
          </svg>
          <span>{db.search_placeholder || 'Buscar cliente…'}</span>
        </div>

        <div style={{ flex: 1 }} />

        {/* + Nuevo cliente button — TARGET DEL CURSOR */}
        <button
          data-target="new-client"
          style={{
            background: pressed
              ? 'linear-gradient(180deg, #0061d4 0%, #0050b3 100%)'
              : (hover ? 'linear-gradient(180deg, #2289ff 0%, #006fe5 100%)' : '#007AFF'),
            color: '#fff',
            border: 0,
            borderRadius: 999,
            padding: '9px 18px',
            fontSize: 12.5,
            fontWeight: 500,
            letterSpacing: -0.005,
            display: 'inline-flex',
            alignItems: 'center',
            gap: 7,
            boxShadow: pressed
              ? 'inset 0 1px 2px rgba(0,0,0,0.2), 0 2px 6px rgba(0, 122, 255, 0.2)'
              : '0 6px 18px rgba(0, 122, 255, 0.28), 0 1px 2px rgba(0, 122, 255, 0.2)',
            transform: pressed ? 'translateY(1px) scale(0.98)' : (hover ? 'translateY(-0.5px)' : 'none'),
            transition: 'transform 120ms, box-shadow 120ms, background 120ms',
            cursor: 'pointer',
            flexShrink: 0,
          }}>
          {db.new_client_btn || '+ Nuevo cliente'}
        </button>
      </div>

      {/* Table */}
      <div style={{
        background: '#fff',
        border: '1px solid #e8e8ed',
        borderRadius: 12,
        overflow: 'hidden',
      }}>
        {/* Table header */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: '2fr 1fr 1.4fr 1fr 1fr 70px',
          gap: 12,
          padding: '10px 18px',
          fontSize: 9.5,
          fontWeight: 600,
          color: '#a1a1a6',
          letterSpacing: 0.14,
          textTransform: 'uppercase',
          background: '#fafafa',
          borderBottom: '1px solid #e8e8ed',
        }}>
          <span>Cliente</span>
          <span>Ocupación</span>
          <span>Creado por</span>
          <span>Fecha</span>
          <span>Estado</span>
          <span style={{ textAlign: 'right' }}>Acción</span>
        </div>

        {/* Injected TOMÁS row — pushes existing rows down */}
        {injectedCase && (
          <div style={{
            height: visibleHeight,
            overflow: 'hidden',
            background: showPulse
              ? `rgba(52, 199, 89, ${0.12 - 0.06 * injE})`
              : (injE >= 1 ? 'rgba(52, 199, 89, 0.06)' : 'transparent'),
            borderBottom: injE > 0.5 ? '1px solid rgba(52, 199, 89, 0.25)' : 'none',
            transition: 'background 240ms',
          }}>
            <div style={{
              display: 'grid',
              gridTemplateColumns: '2fr 1fr 1.4fr 1fr 1fr 70px',
              gap: 12,
              padding: '12px 18px',
              height: rowH,
              boxSizing: 'border-box',
              fontSize: 12.5,
              color: '#1d1d1f',
              letterSpacing: -0.005,
              alignItems: 'center',
              opacity: injE,
              transform: `translateX(${(1 - injE) * -16}px)`,
              willChange: 'opacity, transform',
            }}>
              <span style={{
                fontWeight: 600,
                color: '#1d1d1f',
                display: 'inline-flex',
                alignItems: 'center',
                gap: 6,
              }}>
                <span style={{ width: 7, height: 7, borderRadius: '50%', background: '#34C759' }} />
                TOMÁS SMITH
              </span>
              <span style={{ color: '#a1a1a6' }}>—</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                Amelia
                <span style={{
                  fontSize: 8.5,
                  color: '#FF9500',
                  background: '#fff5e6',
                  border: '1px solid #ffd9a3',
                  padding: '1px 5px',
                  borderRadius: 3,
                  fontWeight: 600,
                  letterSpacing: 0.04,
                }}>OWNER</span>
              </span>
              <span style={{ color: '#6e6e73', fontFamily: 'ui-monospace, monospace', fontSize: 11 }}>2026-05-16</span>
              <span style={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: 4,
                padding: '3px 9px',
                borderRadius: 999,
                fontSize: 10.5,
                color: '#7c3aed',
                background: 'rgba(139, 92, 246, 0.10)',
                border: '1px solid rgba(139, 92, 246, 0.30)',
                fontWeight: 500,
                justifySelf: 'start',
              }}>● Contrato enviado</span>
              <a style={{
                color: '#007AFF',
                fontSize: 12,
                textAlign: 'right',
                fontWeight: 500,
              }}>Ver</a>
            </div>
          </div>
        )}

        {RECENT_CASOS.map((c, i) => (
          <div key={c.id} style={{
            display: 'grid',
            gridTemplateColumns: '2fr 1fr 1.4fr 1fr 1fr 70px',
            gap: 12,
            padding: '12px 18px',
            fontSize: 12.5,
            color: '#1d1d1f',
            letterSpacing: -0.005,
            borderTop: i > 0 ? '1px solid #f5f5f7' : 'none',
            alignItems: 'center',
          }}>
            <span style={{ fontWeight: 500 }}>{c.cliente}</span>
            <span style={{ color: '#a1a1a6' }}>{c.ocupacion}</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              {c.creado}
              <span style={{
                fontSize: 8.5,
                color: '#FF9500',
                background: '#fff5e6',
                border: '1px solid #ffd9a3',
                padding: '1px 5px',
                borderRadius: 3,
                fontWeight: 600,
                letterSpacing: 0.04,
              }}>OWNER</span>
            </span>
            <span style={{ color: '#6e6e73', fontFamily: 'ui-monospace, monospace', fontSize: 11 }}>{c.fecha}</span>
            <span style={{
              display: 'inline-flex',
              alignItems: 'center',
              gap: 4,
              padding: '3px 9px',
              borderRadius: 999,
              fontSize: 10.5,
              color: '#FF9500',
              background: '#fff5e6',
              border: '1px solid #ffd9a3',
              fontWeight: 500,
              alignSelf: 'start',
              justifySelf: 'start',
            }}>
              <span style={{ fontFamily: 'ui-monospace, monospace' }}>≡</span>
              {db[c.estadoKey] || c.estado}
            </span>
            <a style={{
              color: '#007AFF',
              fontSize: 12,
              textAlign: 'right',
              textDecoration: 'none',
              fontWeight: 500,
            }}>Ver</a>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { DashboardHome });
