// WealthIntelligence — shared UI components
const { useState, useEffect, useMemo, useRef, useCallback } = React;

// ------- Icons (line set) -------
const Icon = ({name, size=18, stroke=1.6, style={}}) => {
  const paths = {
    home: <path d="M3 10.5 12 3l9 7.5M5 9v11h4v-7h6v7h4V9"/>,
    inventory: <path d="M3 7h18M3 12h18M3 17h18"/>,
    people: <><circle cx="9" cy="8" r="3"/><path d="M3 20c0-3 3-5 6-5s6 2 6 5"/><circle cx="17" cy="6" r="2"/><path d="M14 20c0-2 2-4 5-4"/></>,
    vault: <><rect x="4" y="6" width="16" height="14" rx="2"/><path d="M9 10v6M15 10v6M9 13h6"/></>,
    informed: <path d="M4 7v13h16V7M2 7l10-4 10 4M9 11v4M15 11v4"/>,
    profile: <><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4.4 3.6-8 8-8s8 3.6 8 8"/></>,
    search: <><circle cx="11" cy="11" r="7"/><path d="m16 16 5 5"/></>,
    plus: <path d="M12 5v14M5 12h14"/>,
    arrow_right: <path d="M5 12h14M13 5l7 7-7 7"/>,
    close: <path d="M6 6l12 12M18 6 6 18"/>,
    check: <path d="m5 12 5 5 9-11"/>,
    chevron_right: <path d="m9 6 6 6-6 6"/>,
    chevron_down: <path d="m6 9 6 6 6-6"/>,
    dot_menu: <><circle cx="5" cy="12" r="1.5"/><circle cx="12" cy="12" r="1.5"/><circle cx="19" cy="12" r="1.5"/></>,
    filter: <path d="M4 6h16M7 12h10M10 18h4"/>,
    shield: <path d="M12 3 4 6v6c0 5 3.5 8 8 9 4.5-1 8-4 8-9V6z"/>,
    mail: <path d="M3 6h18v12H3zm0 0 9 7 9-7"/>,
    lock: <><rect x="4" y="10" width="16" height="10" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/></>,
    unlock: <><rect x="4" y="10" width="16" height="10" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0"/></>,
    clock: <><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></>,
    eye_off: <path d="M3 3l18 18M10 6a9 9 0 0 1 11 6 10 10 0 0 1-2 3M6.5 7.5A10 10 0 0 0 3 12a9 9 0 0 0 13 5M9.5 9.5a3.5 3.5 0 0 0 5 5"/>,
    sparkle: <path d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5 18 18M6 18l2.5-2.5M15.5 8.5 18 6"/>,
    bell: <><path d="M6 16V11a6 6 0 0 1 12 0v5l2 2H4z"/><path d="M10 20a2 2 0 0 0 4 0"/></>,
    settings: <><circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M4.2 4.2l2.1 2.1M17.7 17.7l2.1 2.1M2 12h3M19 12h3M4.2 19.8l2.1-2.1M17.7 6.3l2.1-2.1"/></>,
    edit: <path d="M14 4l6 6-11 11H3v-6zM13 5l6 6"/>,
    trash: <path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13M10 11v6M14 11v6"/>,
    alert: <><circle cx="12" cy="12" r="9"/><path d="M12 7v6M12 16v.5"/></>,
    activity: <path d="M3 12h4l3-8 4 16 3-8h4"/>,
    medkit: <><rect x="3" y="7" width="18" height="13" rx="2"/><path d="M9 7V4h6v3M12 11v6M9 14h6"/></>,
    key: <><circle cx="7" cy="12" r="3"/><path d="M10 12h11M17 12v4M21 12v3"/></>,
  };
  return React.createElement('svg', {
    width:size, height:size, viewBox:'0 0 24 24', fill:'none',
    stroke:'currentColor', strokeWidth:stroke, strokeLinecap:'round', strokeLinejoin:'round',
    style,
  }, paths[name] || null);
};

// ------- Monogram -------
const Monogram = ({name, color='#307D86', initials, size='md'}) => {
  const init = initials || (name||'').split(' ').map(w=>w[0]).join('').slice(0,2).toUpperCase();
  return <span className={`mono ${size==='sm'?'mono-sm':size==='lg'?'mono-lg':size==='xl'?'mono-xl':''}`} style={{background:color}}>{init}</span>;
};

// ------- Stacked monograms -------
const MonoStack = ({people, size='sm', max=3}) => {
  if (!people || !people.length) return null;
  const shown = people.slice(0, max);
  const more = people.length - max;
  return <span className="mono-stack">
    {shown.map(p => <Monogram key={p.id} color={p.color} initials={p.initials} size={size} />)}
    {more > 0 && <span className={`mono ${size==='sm'?'mono-sm':''}`} style={{background:'var(--gr-100)', color:'var(--ink-muted)'}}>+{more}</span>}
  </span>;
};

// ------- Cassetta icon badge -------
const CassettaBadge = ({icon, color, size=38}) => (
  <span className="cassetta-icon" style={{
    width:size, height:size, borderRadius:Math.round(size*0.27),
    background:color, fontSize:Math.round(size*0.5),
  }}>{icon}</span>
);

// ------- Trigger badge -------
const TriggerBadge = ({trigger, t, short=false}) => {
  const cls = trigger==='temporary' ? 'temporary' : 'permanent';
  const label = short
    ? t.vault.triggers[`${cls}_short`]
    : t.vault.triggers[cls];
  return <span className={`trigger-badge ${cls}`}>
    <span className={`trigger-dot ${cls}`}/>
    {label}
  </span>;
};

// ------- Sidebar -------
const Sidebar = ({route, setRoute, t, state}) => {
  const unassignedItems = state.inventory.filter(it => !state.cassette.some(c => c.itemIds.includes(it.id))).length;
  const items = [
    {id:'home',        icon:'home',        label:t.nav.home},
    {id:'inventory',   icon:'inventory',   label:t.nav.inventory,   badge: unassignedItems || null},
    {id:'trustworthy', icon:'people',      label:t.nav.trustworthy},
    {id:'vault',       icon:'vault',       label:t.nav.vault,       badge: state.cassette.length},
    {id:'informed',    icon:'informed',    label:t.nav.informed,    count: state.informed?.length || 0},
    {id:'profile',     icon:'profile',     label:t.nav.profile},
  ];
  return <aside style={{
    background:'var(--paper-2)', borderRight:'1px solid var(--line)',
    padding:'28px 20px', display:'flex', flexDirection:'column', gap:8,
    position:'sticky', top:0, height:'100vh', zIndex:5,
  }}>
    <div style={{display:'flex', alignItems:'baseline', gap:6, padding:'4px 8px 24px', flexWrap:'wrap'}}>
      <span className="t-display" style={{fontSize:24, lineHeight:1}}>Wealth</span>
      <span style={{fontFamily:'var(--f-serif)', fontStyle:'italic', fontSize:24, color:'var(--accent)', lineHeight:1}}>Intelligence</span>
    </div>

    {items.map(item => (
      <a key={item.id} className={`nav-link ${route===item.id?'active':''}`} onClick={()=>setRoute(item.id)}>
        <Icon name={item.icon} size={18} />
        <span className="grow">{item.label}</span>
        {item.badge ? <span className="chip chip-muted" style={{padding:'2px 8px', fontSize:11}}>{item.badge}</span> : null}
        {item.count ? <span className="dot" style={{right:14, background:'var(--accent)'}}></span> : null}
      </a>
    ))}

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

    {state.temporaryIllness?.active && (
      <div className="card" style={{padding:14, background:'var(--trigger-temporary-soft)', borderColor:'transparent'}}>
        <div className="t-eyebrow" style={{marginBottom:6, color:'var(--trigger-temporary)'}}>Stato</div>
        <div className="row" style={{gap:8}}>
          <Icon name="medkit" size={18} style={{color:'var(--trigger-temporary)'}}/>
          <span style={{fontSize:13, fontWeight:500, color:'var(--trigger-temporary)'}}>Inf. temporanea attiva</span>
        </div>
      </div>
    )}

    <div className="card" style={{padding:14, background:'#fff'}}>
      <div className="t-eyebrow" style={{marginBottom:8}}>{t.home.plan_title}</div>
      <div className="row" style={{justifyContent:'space-between', marginBottom:8}}>
        <span style={{fontFamily:'var(--f-serif)', fontStyle:'italic', fontSize:28}}>{state.profileProgress}<span style={{fontSize:16, color:'var(--ink-muted)'}}>%</span></span>
        <Icon name="sparkle" size={16} stroke={1.4} style={{color:'var(--accent)'}}/>
      </div>
      <div className="progress"><div style={{width:state.profileProgress+'%'}}/></div>
    </div>

    <div className="row" style={{padding:'12px 8px', gap:10}}>
      <Monogram name={state.user.name} color={state.user.color} initials={state.user.initials} size="sm"/>
      <div style={{lineHeight:1.15, fontSize:13}}>
        <div style={{fontWeight:500}}>{state.user.name}</div>
        <div className="muted" style={{fontSize:11}}>{state.user.email}</div>
      </div>
    </div>
  </aside>;
};

// ------- Page header -------
const PageHeader = ({eyebrow, title, subtitle, actions}) => {
  return <div style={{marginBottom:32}}>
    {eyebrow && <div className="t-eyebrow" style={{marginBottom:12}}>{eyebrow}</div>}
    <div className="row" style={{alignItems:'flex-end', justifyContent:'space-between', gap:24, flexWrap:'wrap'}}>
      <div>
        <h1 className="t-display" style={{fontSize:56, margin:0}}>{title}</h1>
        {subtitle && <p className="muted" style={{margin:'22px 0 0', maxWidth:640, fontSize:15}}>{subtitle}</p>}
      </div>
      {actions && <div className="row" style={{gap:10}}>{actions}</div>}
    </div>
  </div>;
};

// ------- Section header -------
const SectionHeader = ({eyebrow, title, action}) => {
  return <div className="row" style={{justifyContent:'space-between', marginBottom:16, alignItems:'flex-end'}}>
    <div>
      {eyebrow && <div className="t-eyebrow" style={{marginBottom:6}}>{eyebrow}</div>}
      {title && <h2 className="t-h1" style={{fontSize:28, margin:0}}>{title}</h2>}
    </div>
    {action}
  </div>;
};

// ------- Inventory item icon (square) -------
const ItemBadge = ({icon, color, size=36}) => (
  <span style={{
    display:'inline-flex', alignItems:'center', justifyContent:'center',
    width:size, height:size, borderRadius:10, background:color, color:'#fff',
    fontWeight:600, fontSize:size>40?18:14, flexShrink:0,
  }}>{icon}</span>
);

// ------- Mini KPI -------
const KpiCell = ({num, label, tone}) => <div>
  <div className="t-num" style={{fontSize:34, lineHeight:1, color: tone==='warn'?'var(--red-600)':'var(--ink)'}}>{num}</div>
  <div className="muted" style={{fontSize:11, letterSpacing:'.08em', textTransform:'uppercase', marginTop:6}}>{label}</div>
</div>;

// ------- Generic dialog header -------
const DialogHeader = ({title, onClose}) => (
  <div className="row" style={{justifyContent:'space-between', padding:'20px 24px', borderBottom:'1px solid var(--line)'}}>
    <h3 style={{margin:0, fontSize:18, fontWeight:600}}>{title}</h3>
    <button className="btn btn-ghost btn-icon" onClick={onClose}><Icon name="close" size={16}/></button>
  </div>
);

// ------- Field wrapper -------
const Field = ({label, help, children}) => (
  <label style={{display:'block', marginBottom:18}}>
    <div style={{fontSize:12, fontWeight:500, marginBottom:4, color:'var(--ink)'}}>{label}</div>
    {help && <div className="muted" style={{fontSize:12, marginBottom:8}}>{help}</div>}
    {children}
  </label>
);

// ------- Helpers -------
const fmtEur = (n, opts={}) => {
  if (typeof n !== 'number') return '—';
  return new Intl.NumberFormat('it-IT', {
    style:'currency', currency:'EUR',
    maximumFractionDigits: opts.decimals ?? 0,
  }).format(n);
};

const fmtDateTime = (iso) => {
  if (!iso) return '';
  try { return new Date(iso).toLocaleString('it-IT', { day:'numeric', month:'short', year:'numeric', hour:'2-digit', minute:'2-digit' }); }
  catch(e){ return iso; }
};

Object.assign(window, {
  Icon, Monogram, MonoStack, CassettaBadge, TriggerBadge, Sidebar,
  PageHeader, SectionHeader, ItemBadge, KpiCell, DialogHeader, Field,
  fmtEur, fmtDateTime,
});
