// Shared components, helpers, formatters
const { useState, useEffect, useMemo, useCallback, useRef, createContext, useContext } = React;

// i18n context
const I18nContext = createContext({ t: (k) => k, lang: 'es', setLang: () => {} });
const useT = () => useContext(I18nContext);

function I18nProvider({ lang, setLang, children }) {
  const dict = window.DIVIDIS_I18N[lang] || window.DIVIDIS_I18N.es;
  const t = useCallback((k) => dict[k] ?? k, [dict]);
  const value = useMemo(() => ({ t, lang, setLang: setLang || (() => {}) }), [t, lang, setLang]);
  return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
}

// Formatters
const fmtEUR = (n, opts = {}) => {
  const decimals = opts.decimals ?? 0;
  return new Intl.NumberFormat('es-ES', { style: 'currency', currency: 'EUR', minimumFractionDigits: decimals, maximumFractionDigits: decimals }).format(n);
};
const fmtNum = (n, opts = {}) => {
  return new Intl.NumberFormat('es-ES', opts).format(n);
};
const fmtPct = (n, decimals = 1) => `${n >= 0 ? '' : ''}${n.toFixed(decimals)}%`;
const fmtDate = (iso, lang = 'es') => {
  const d = new Date(iso);
  return d.toLocaleDateString(lang === 'es' ? 'es-ES' : 'en-GB', { day: '2-digit', month: 'short', year: 'numeric' });
};

// Type label
const typeLabel = (type, t) => {
  switch (type) {
    case 'invoice': return t('mkt_filter_invoice');
    case 'fixed': return t('mkt_filter_fixed');
    case 'equity': return t('mkt_filter_equity');
    case 'seed': return t('mkt_filter_seed');
    default: return type;
  }
};

// Term label
const termLabel = (opp, t) => {
  const unit = opp.termUnit === 'days' ? t('days') : opp.termUnit === 'months' ? t('months') : t('years');
  return `${opp.term} ${unit}`;
};

// Risk to label
const riskLabel = (risk, lang) => {
  const map = {
    'very-low': { es: 'Muy bajo', en: 'Very low' },
    'low': { es: 'Bajo', en: 'Low' },
    'medium': { es: 'Medio', en: 'Medium' },
    'medium-high': { es: 'Medio-alto', en: 'Medium-high' },
    'high': { es: 'Alto', en: 'High' },
  };
  return (map[risk] || {})[lang] || risk;
};

// Icon (institutional minimal — no emoji)
function Icon({ name, size = 16, color = 'currentColor' }) {
  const s = size;
  const props = { width: s, height: s, viewBox: '0 0 24 24', fill: 'none', stroke: color, strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (name) {
    case 'invoice': return <svg {...props}><path d="M5 3h11l3 3v15a0 0 0 0 1 0 0H5a0 0 0 0 1 0 0V3z"/><path d="M9 9h6M9 13h6M9 17h4"/></svg>;
    case 'equity': return <svg {...props}><path d="M3 17l6-6 4 4 8-8"/><path d="M14 7h7v7"/></svg>;
    case 'fixed': return <svg {...props}><rect x="3" y="6" width="18" height="13" rx="1"/><path d="M3 11h18M7 6V4M17 6V4"/></svg>;
    case 'seed': return <svg {...props}><path d="M12 20v-8"/><path d="M12 12c-3 0-6-2-6-6 3 0 6 2 6 6z"/><path d="M12 12c3 0 6-2 6-6-3 0-6 2-6 6z"/></svg>;
    case 'bell': return <svg {...props}><path d="M6 8a6 6 0 0 1 12 0v5l1.5 3h-15L6 13V8z"/><path d="M10 19a2 2 0 0 0 4 0"/></svg>;
    case 'search': return <svg {...props}><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>;
    case 'chevron-down': return <svg {...props}><path d="m6 9 6 6 6-6"/></svg>;
    case 'chevron-right': return <svg {...props}><path d="m9 6 6 6-6 6"/></svg>;
    case 'chevron-left': return <svg {...props}><path d="m15 6-6 6 6 6"/></svg>;
    case 'arrow-up': return <svg {...props}><path d="M12 19V5M5 12l7-7 7 7"/></svg>;
    case 'arrow-down': return <svg {...props}><path d="M12 5v14M19 12l-7 7-7-7"/></svg>;
    case 'arrow-right': return <svg {...props}><path d="M5 12h14M12 5l7 7-7 7"/></svg>;
    case 'check': return <svg {...props}><path d="M5 12l5 5L20 7"/></svg>;
    case 'x': return <svg {...props}><path d="M18 6 6 18M6 6l12 12"/></svg>;
    case 'shield': return <svg {...props}><path d="M12 3 4 6v6c0 5 4 8 8 9 4-1 8-4 8-9V6l-8-3z"/></svg>;
    case 'lock': return <svg {...props}><rect x="4" y="11" width="16" height="10" rx="1"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>;
    case 'doc': return <svg {...props}><path d="M14 3H6v18h12V7l-4-4z"/><path d="M14 3v4h4"/></svg>;
    case 'building': return <svg {...props}><rect x="4" y="3" width="16" height="18" rx="1"/><path d="M9 8h2M13 8h2M9 12h2M13 12h2M9 16h2M13 16h2"/></svg>;
    case 'users': return <svg {...props}><circle cx="9" cy="8" r="3"/><circle cx="17" cy="9" r="2"/><path d="M3 20c0-3 2.5-5 6-5s6 2 6 5M15 20c0-2 1.5-4 4-4s4 1 4 3"/></svg>;
    case 'calendar': return <svg {...props}><rect x="3" y="5" width="18" height="16" rx="1"/><path d="M3 10h18M8 3v4M16 3v4"/></svg>;
    case 'plus': return <svg {...props}><path d="M12 5v14M5 12h14"/></svg>;
    case 'menu': return <svg {...props}><path d="M4 7h16M4 12h16M4 17h16"/></svg>;
    case 'filter': return <svg {...props}><path d="M3 5h18l-7 9v6l-4-2v-4L3 5z"/></svg>;
    case 'grid': return <svg {...props}><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg>;
    case 'list': return <svg {...props}><path d="M3 6h18M3 12h18M3 18h18"/></svg>;
    case 'spark': return <svg {...props}><path d="M12 2v4M12 18v4M2 12h4M18 12h4M5 5l3 3M16 16l3 3M5 19l3-3M16 8l3-3"/></svg>;
    case 'globe': return <svg {...props}><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a13 13 0 0 1 0 18M12 3a13 13 0 0 0 0 18"/></svg>;
    case 'logout': return <svg {...props}><path d="M9 4H5a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h4M16 17l5-5-5-5M21 12H9"/></svg>;
    case 'pdf': return <svg {...props}><path d="M14 3H6v18h12V7l-4-4z"/><path d="M14 3v4h4M9 13h6M9 17h4"/></svg>;
    case 'pen': return <svg {...props}><path d="M16 3l5 5L8 21H3v-5L16 3z"/></svg>;
    case 'card': return <svg {...props}><rect x="3" y="6" width="18" height="13" rx="1"/><path d="M3 10h18"/></svg>;
    case 'mail': return <svg {...props}><rect x="3" y="5" width="18" height="14" rx="1"/><path d="M3 7l9 7 9-7"/></svg>;
    case 'chart': return <svg {...props}><path d="M3 21h18"/><path d="M6 17V11M11 17V7M16 17v-4M21 17V9"/></svg>;
    case 'bank': return <svg {...props}><path d="M3 9l9-6 9 6"/><path d="M3 9h18M5 9v9M19 9v9M9 12v5M15 12v5M3 21h18"/></svg>;
    case 'seedling': return <svg {...props}><path d="M12 21v-8"/><path d="M12 13c-3 0-6-2-6-6 3 0 6 2 6 6z"/><path d="M12 13c3 0 6-2 6-6-3 0-6 2-6 6z"/></svg>;
    case 'logo':
      return (
        <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
          <rect x="2" y="2" width="20" height="20" rx="5" fill="url(#lg)"/>
          <path d="M7 17V7h4a5 5 0 0 1 0 10H7z" fill="#0A0D14"/>
          <path d="M11 9.5h-2v5h2a2.5 2.5 0 0 0 0-5z" fill="url(#lg)"/>
          <defs>
            <linearGradient id="lg" x1="0" y1="0" x2="24" y2="24">
              <stop offset="0" stopColor="#4BD193"/>
              <stop offset="1" stopColor="#1c8a5c"/>
            </linearGradient>
          </defs>
        </svg>
      );
    default: return null;
  }
}

// Logo word-mark
function Logo({ size = 22, sub }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <Icon name="logo" size={26} />
      <div style={{ fontFamily: 'var(--serif)', fontSize: size, letterSpacing: '-0.02em', color: 'var(--text)', display: 'flex', alignItems: 'baseline' }}>
        Dividis<span style={{ color: 'var(--emerald)' }}>.</span><span style={{ fontWeight: 400, fontSize: size * 0.95, opacity: 0.85 }}>Capital</span>
      </div>
      {sub ? <span style={{ fontSize: 12, color: 'var(--text-3)', borderLeft: '1px solid var(--line-2)', paddingLeft: 12, marginLeft: 2 }}>{sub}</span> : null}
    </div>
  );
}

// Type icon
function TypeIcon({ type, size = 14 }) {
  const colors = {
    invoice: '#8DAFEF',
    fixed: 'var(--emerald-2)',
    equity: 'var(--gold)',
    seed: '#F38A8E',
  };
  return <Icon name={type} size={size} color={colors[type] || 'currentColor'} />;
}

// Type badge
function TypeBadge({ type }) {
  const { t } = useT();
  return (
    <span className={`badge badge-${type}`}>
      <TypeIcon type={type} size={12} />
      {typeLabel(type, t)}
    </span>
  );
}

// Risk pill
function RiskPill({ risk }) {
  const { lang } = useT();
  return (
    <span className={`risk risk-${risk}`}>
      <span className="risk-dot" />
      {riskLabel(risk, lang)}
    </span>
  );
}

// Rating badge
function RatingBadge({ rating }) {
  // Color by tier
  const firstLetter = rating[0];
  const color = firstLetter === 'A' ? 'var(--emerald-2)'
    : firstLetter === 'B' ? 'var(--gold)'
    : firstLetter === 'C' ? 'var(--amber)'
    : 'var(--red)';
  return (
    <span className="badge badge-rating" style={{ background: 'rgba(255,255,255,0.04)', borderColor: 'var(--line-2)', color, padding: '3px 8px' }}>
      {rating}
    </span>
  );
}

// Sparkline SVG
function Sparkline({ values, width = 80, height = 24, color = 'var(--emerald-2)' }) {
  if (!values || values.length === 0) return null;
  const min = Math.min(...values);
  const max = Math.max(...values);
  const range = max - min || 1;
  const step = width / (values.length - 1);
  const points = values.map((v, i) => `${i * step},${height - ((v - min) / range) * height}`).join(' ');
  return (
    <svg width={width} height={height}>
      <polyline points={points} fill="none" stroke={color} strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round" />
    </svg>
  );
}

// Top Nav component
function TopNav({ route, onNavigate, lang, onLangToggle }) {
  const { t } = useT();
  const links = [
    { id: 'landing', label: t('nav_landing') },
    { id: 'marketplace', label: t('nav_marketplace') },
    { id: 'portfolio', label: t('nav_portfolio') },
    { id: 'company', label: t('nav_dashboard') },
    { id: 'admin', label: t('nav_admin') },
  ];
  return (
    <nav className="nav">
      <div className="nav-left">
        <div onClick={() => onNavigate('landing')} style={{ cursor: 'pointer' }}>
          <Logo size={20} />
        </div>
        <div className="nav-links">
          {links.map(l => (
            <button
              key={l.id}
              className={`nav-link ${route.startsWith(l.id) ? 'active' : ''}`}
              onClick={() => onNavigate(l.id)}
            >
              {l.label}
            </button>
          ))}
        </div>
      </div>
      <div className="nav-right">
        <button className="nav-icon-btn" onClick={onLangToggle} title="Toggle language" style={{ width: 'auto', padding: '0 12px', fontSize: 12, fontWeight: 600, letterSpacing: '0.06em' }}>
          {lang.toUpperCase()}
        </button>
        <button className="nav-icon-btn" title="Search">
          <Icon name="search" size={15} />
        </button>
        <button className="nav-icon-btn" title="Notifications">
          <Icon name="bell" size={15} />
          <span className="dot-notif" />
        </button>
        <div className="avatar">AL</div>
      </div>
    </nav>
  );
}

// Toast manager
const ToastContext = createContext({ show: () => {} });
function ToastProvider({ children }) {
  const [msg, setMsg] = useState(null);
  const show = useCallback((m) => {
    setMsg(m);
    setTimeout(() => setMsg(null), 3200);
  }, []);
  return (
    <ToastContext.Provider value={{ show }}>
      {children}
      {msg ? <div className="toast">{msg}</div> : null}
    </ToastContext.Provider>
  );
}
const useToast = () => useContext(ToastContext);

// Export to window
Object.assign(window, {
  useT, I18nProvider, ToastProvider, useToast,
  fmtEUR, fmtNum, fmtPct, fmtDate, typeLabel, termLabel, riskLabel,
  Icon, Logo, TypeIcon, TypeBadge, RiskPill, RatingBadge, Sparkline, TopNav,
});
