// product-ui.jsx — Faithful CBAMy product widgets (dashboard, simulator, declaration)
// All rendered as React. Used in landing variants as "Cosa vedi" snippets.

const { useState: _useState, useEffect: _useEffect, useMemo: _useMemo } = React;

// ─── App-chrome: sidebar + main wrap ────────────────────────────────────────
function CBAMSidebar({ active = 'Dashboard', compact = false, scale = 1 }) {
  const items = [
    { g: 'OPERATIVITÀ', items: [
      { n: 'Dashboard', ic: IconGrid },
      { n: 'Dichiarazioni', ic: IconDoc },
      { n: 'Simulatore', ic: IconCalc },
    ]},
    { g: 'AMMINISTRAZIONE', items: [
      { n: 'Utenti', ic: IconUsers },
      { n: 'Regole CBAM', ic: IconGear },
      { n: 'Dataset normativi', ic: IconDb },
      { n: 'Prezzo certificato', ic: IconEuro },
      { n: 'Documenti legali', ic: IconScale },
      { n: 'Dichiarazione test', ic: IconFlask },
    ]},
  ];
  return (
    <aside style={{
      width: compact ? 200 : 232, flex: '0 0 auto',
      borderRight: '1px solid var(--line)',
      background: 'var(--bg-soft)',
      padding: '22px 14px',
      fontSize: 13,
      display: 'flex', flexDirection: 'column',
      minHeight: '100%',
      fontFamily: 'var(--font-sans)',
    }}>
      <div style={{ padding: '0 8px 22px', fontFamily: 'var(--font-serif)', fontSize: 17, fontWeight: 600, color: 'var(--ink)' }}>
        CBAM Manager
      </div>
      {items.map((grp, gi) => (
        <div key={gi} style={{ marginBottom: 18 }}>
          <div style={{
            padding: '4px 10px 8px', fontSize: 10.5, fontWeight: 600,
            letterSpacing: '0.13em', color: 'var(--ink-dim)',
          }}>{grp.g}</div>
          {grp.items.map(it => {
            const isActive = it.n === active;
            return (
              <div key={it.n} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '8px 10px', borderRadius: 7,
                color: isActive ? 'var(--ink)' : 'var(--ink-soft)',
                background: isActive ? '#fff' : 'transparent',
                border: isActive ? '1px solid var(--teal-300)' : '1px solid transparent',
                fontWeight: isActive ? 600 : 500,
                cursor: 'default',
              }}>
                <it.ic size={15} color={isActive ? 'var(--accent)' : 'var(--ink-mute)'} />
                <span>{it.n}</span>
              </div>
            );
          })}
        </div>
      ))}
      <div style={{ flex: 1 }} />
      <div style={{ borderTop: '1px solid var(--line)', paddingTop: 12, marginTop: 8 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 8px' }}>
          <div style={{
            width: 24, height: 24, borderRadius: '50%', background: 'var(--slate-200)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 11, fontWeight: 600, color: 'var(--ink-soft)',
          }}>C</div>
          <span style={{ fontSize: 12, color: 'var(--ink-soft)' }}>cmcurzel@gmail.com</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 8px', color: 'var(--ink-mute)' }}>
          <IconLogout size={14} /> <span style={{ fontSize: 12 }}>Esci</span>
        </div>
      </div>
    </aside>
  );
}

// ─── Icons (line, 1.5 stroke) ───────────────────────────────────────────────
const ico = (size, children) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
       strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block', flex: '0 0 auto' }}>
    {children}
  </svg>
);
function IconGrid({ size = 16, color }) { return <span style={{color}}>{ico(size, <><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></>)}</span>; }
function IconDoc({ size = 16, color }) { return <span style={{color}}>{ico(size, <><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><polyline points="14 3 14 9 20 9"/></>)}</span>; }
function IconCalc({ size = 16, color }) { return <span style={{color}}>{ico(size, <><rect x="4" y="3" width="16" height="18" rx="2"/><line x1="8" y1="7" x2="16" y2="7"/><line x1="8" y1="12" x2="9" y2="12"/><line x1="12" y1="12" x2="13" y2="12"/><line x1="16" y1="12" x2="16" y2="12"/><line x1="8" y1="16" x2="9" y2="16"/><line x1="12" y1="16" x2="16" y2="16"/></>)}</span>; }
function IconUsers({ size = 16, color }) { return <span style={{color}}>{ico(size, <><path d="M17 21v-2a4 4 0 0 0-4-4H7a4 4 0 0 0-4 4v2"/><circle cx="10" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></>)}</span>; }
function IconGear({ size = 16, color }) { return <span style={{color}}>{ico(size, <><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.13.3.4.51.74.6.34.09.7.04 1-.13l.05-.03a2 2 0 1 1 1.94 3.49l-.05.03a1.65 1.65 0 0 0-.99 1.32z"/></>)}</span>; }
function IconDb({ size = 16, color }) { return <span style={{color}}>{ico(size, <><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/></>)}</span>; }
function IconEuro({ size = 16, color }) { return <span style={{color}}>{ico(size, <><path d="M18 5.5a8 8 0 1 0 0 13"/><line x1="4" y1="10" x2="13" y2="10"/><line x1="4" y1="14" x2="12" y2="14"/></>)}</span>; }
function IconScale({ size = 16, color }) { return <span style={{color}}>{ico(size, <><path d="M3 7h18"/><path d="M12 3v18"/><path d="M7 7l-3 6a3 3 0 0 0 6 0z"/><path d="M17 7l-3 6a3 3 0 0 0 6 0z"/><path d="M8 21h8"/></>)}</span>; }
function IconFlask({ size = 16, color }) { return <span style={{color}}>{ico(size, <><path d="M9 3h6"/><path d="M10 3v6L4 19a2 2 0 0 0 1.8 3h12.4a2 2 0 0 0 1.8-3L14 9V3"/><path d="M7 14h10"/></>)}</span>; }
function IconLogout({ size = 16, color }) { return <span style={{color}}>{ico(size, <><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></>)}</span>; }
function IconUpload({ size = 16, color }) { return <span style={{color}}>{ico(size, <><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></>)}</span>; }
function IconPlus({ size = 16, color }) { return <span style={{color}}>{ico(size, <><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></>)}</span>; }
function IconCheck({ size = 16, color }) { return <span style={{color}}>{ico(size, <polyline points="20 6 9 17 4 12"/>)}</span>; }
function IconCheckCircle({ size = 16, color }) { return <span style={{color}}>{ico(size, <><circle cx="12" cy="12" r="10"/><polyline points="9 12 12 15 16 9"/></>)}</span>; }
function IconInfo({ size = 14, color }) { return <span style={{color}}>{ico(size, <><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></>)}</span>; }
function IconAlert({ size = 14, color }) { return <span style={{color}}>{ico(size, <><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></>)}</span>; }
function IconChevron({ size = 16, color, dir = 'down' }) {
  const pts = { down: '6 9 12 15 18 9', up: '6 15 12 9 18 15', right: '9 6 15 12 9 18' }[dir];
  return <span style={{color}}>{ico(size, <polyline points={pts}/>)}</span>;
}
function IconArrowRight({ size = 16, color }) { return <span style={{color}}>{ico(size, <><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></>)}</span>; }
function IconFile({ size = 16, color }) { return <span style={{color}}>{ico(size, <><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></>)}</span>; }
function IconLock({ size = 16, color }) { return <span style={{color}}>{ico(size, <><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></>)}</span>; }

// ─── Dashboard KPI card ──────────────────────────────────────────────────────
function KPI({ label, value, unit, sub, info = true }) {
  return (
    <div style={{ minWidth: 0 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8, fontSize: 13, color: 'var(--ink-soft)' }}>
        <span>{label}</span>
        {info && <IconInfo size={13} color="var(--ink-dim)" />}
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
        <span className="num" style={{ fontSize: 38, color: 'var(--ink)', lineHeight: 1 }}>{value}</span>
        {unit && <span className="mono" style={{ fontSize: 13, color: 'var(--ink-mute)' }}>{unit}</span>}
      </div>
      {sub && <div style={{ marginTop: 8, fontSize: 12, color: 'var(--ink-mute)' }}>{sub}</div>}
    </div>
  );
}

// ─── Threshold progress bar (like the screenshot) ──────────────────────────
function SogliaBar({ value = 9.37, max = 50, label = 'Soglia importazioni CBAM', sub }) {
  const pct = Math.min(100, (value / max) * 100);
  const under = value < max;
  return (
    <div style={{
      padding: '16px 20px', borderRadius: 10, background: 'var(--bg-muted)',
      display: 'flex', flexDirection: 'column', gap: 12, border: '1px solid var(--line-soft)',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16 }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: 'var(--ink-soft)' }}>
            <span>{label}</span> <IconInfo size={13} color="var(--ink-dim)" />
          </div>
          <div style={{ marginTop: 3, fontSize: 12, color: 'var(--ink-mute)' }}>
            {sub || (under ? 'Sotto la soglia — obblighi ridotti' : 'Sopra la soglia — calcolo CBAM attivo')}
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
          <span className="num" style={{ fontSize: 26, color: 'var(--ink)' }}>{fmtN(value, 2).replace('.', ',')}</span>
          <span className="mono" style={{ fontSize: 13, color: 'var(--ink-mute)' }}> / {max} t</span>
        </div>
      </div>
      <div style={{ height: 8, borderRadius: 4, background: 'var(--slate-200)', overflow: 'hidden' }}>
        <div style={{
          width: `${pct}%`, height: '100%',
          background: 'linear-gradient(90deg, var(--teal-400) 0%, var(--teal-600) 100%)',
          transition: 'width .6s cubic-bezier(.2,.7,.3,1)',
        }} />
      </div>
    </div>
  );
}

// ─── Donut ──────────────────────────────────────────────────────────────────
function Donut({ data, size = 200, thickness = 26, legend = true, title, subtitle }) {
  const total = data.reduce((s, d) => s + d.v, 0);
  const r = (size - thickness) / 2;
  const cx = size / 2, cy = size / 2;
  let acc = 0;
  const arcs = data.map((d) => {
    const start = acc / total * Math.PI * 2 - Math.PI / 2;
    acc += d.v;
    const end = acc / total * Math.PI * 2 - Math.PI / 2;
    const large = end - start > Math.PI ? 1 : 0;
    const x1 = cx + r * Math.cos(start), y1 = cy + r * Math.sin(start);
    const x2 = cx + r * Math.cos(end),   y2 = cy + r * Math.sin(end);
    return { ...d, path: `M ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2}` };
  });
  return (
    <div>
      {title && <div style={{ fontSize: 15, fontWeight: 500, color: 'var(--ink)' }}>{title}</div>}
      {subtitle && <div style={{ fontSize: 12, color: 'var(--ink-mute)', marginTop: 2 }}>{subtitle}</div>}
      <svg width={size} height={size} style={{ display: 'block', margin: '14px auto 0' }}>
        {arcs.map((a, i) => (
          <path key={i} d={a.path} stroke={a.color} strokeWidth={thickness} fill="none" strokeLinecap="butt"/>
        ))}
      </svg>
      {legend && (
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center', marginTop: 12, fontSize: 12 }}>
          {data.map(d => (
            <span key={d.label} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--ink-soft)' }}>
              <span style={{ width: 9, height: 9, background: d.color, borderRadius: 2 }} /> {d.label}
            </span>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── Bar chart (trimestri) ──────────────────────────────────────────────────
function Bars({ data, height = 140, title, subtitle, color = 'var(--accent)' }) {
  const max = Math.max(...data.map(d => d.v));
  return (
    <div>
      {title && <div style={{ fontSize: 15, fontWeight: 500, color: 'var(--ink)' }}>{title}</div>}
      {subtitle && <div style={{ fontSize: 12, color: 'var(--ink-mute)', marginTop: 2 }}>{subtitle}</div>}
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 14, marginTop: 18, height }}>
        {data.map((d, i) => (
          <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
            <div style={{ flex: 1, width: '100%', display: 'flex', alignItems: 'flex-end' }}>
              <div style={{
                width: '100%',
                height: `${(d.v / max) * 100}%`,
                background: d.color || color,
                borderRadius: '4px 4px 0 0',
                position: 'relative',
              }}>
                <span className="mono" style={{
                  position: 'absolute', top: -18, left: '50%', transform: 'translateX(-50%)',
                  fontSize: 11, color: 'var(--ink-soft)', whiteSpace: 'nowrap',
                }}>{d.v}</span>
              </div>
            </div>
            <span style={{ fontSize: 11, color: 'var(--ink-mute)' }}>{d.label}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Declaration line (riga CBAM) ──────────────────────────────────────────
function DeclLine({ cn, country = 'CN', kg, desc, eur, certs, mode = 'Valori default', highlight = false }) {
  return (
    <div style={{
      padding: '16px 18px',
      border: `1px solid ${highlight ? 'var(--accent)' : 'var(--line)'}`,
      borderRadius: 10,
      display: 'grid', gridTemplateColumns: '1fr auto', gap: 14, alignItems: 'start',
      background: '#fff',
      boxShadow: highlight ? '0 0 0 4px rgba(13,148,136,0.10)' : 'none',
      position: 'relative',
    }}>
      <div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, flexWrap: 'wrap' }}>
          <span className="mono" style={{ fontWeight: 600, fontSize: 15, color: 'var(--ink)' }}>{cn}</span>
          <span className="mono" style={{ fontSize: 12, color: 'var(--ink-mute)' }}>{country}</span>
          <span className="mono" style={{ fontSize: 12, color: 'var(--ink-mute)' }}>{kg} kg</span>
        </div>
        <div style={{ marginTop: 6, fontSize: 13, color: 'var(--ink-soft)', lineHeight: 1.5, maxWidth: 460 }}>{desc}</div>
        <div style={{ marginTop: 8, fontSize: 12, color: 'var(--ink-mute)' }}>
          Valori default — se disponi dei dati reali del produttore puoi ricalcolare
        </div>
      </div>
      <div style={{ textAlign: 'right', display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
          <span className="num" style={{ fontSize: 18 }}>{eur}</span>
          <span className="mono" style={{ fontSize: 11, color: 'var(--ink-mute)' }}>EUR</span>
        </div>
        <span className="mono" style={{ fontSize: 11, color: 'var(--ink-mute)' }}>{certs} cert.</span>
        <div style={{
          marginTop: 4, padding: '4px 8px', borderRadius: 999,
          background: 'var(--accent-bg)', color: 'var(--accent-ink)',
          fontSize: 11, fontWeight: 500, display: 'inline-flex', alignItems: 'center', gap: 4,
        }}>
          <IconCheckCircle size={11}/> {mode}
        </div>
      </div>
    </div>
  );
}

// ─── Simulator inputs preview (compact) ─────────────────────────────────────
function SimField({ label, value, placeholder, unit, hint, w, mono = true, cls }) {
  return (
    <div style={{ minWidth: 0 }}>
      <label style={{ display: 'flex', alignItems: 'baseline', gap: 6, fontSize: 12.5, color: 'var(--ink-soft)', marginBottom: 6 }}>
        <span>{label}</span>
        {unit && <span className="mono" style={{ fontSize: 11, color: 'var(--ink-mute)' }}>({unit})</span>}
      </label>
      <div style={{
        padding: '9px 12px', border: '1px solid var(--line)', borderRadius: 8,
        background: cls === 'filled' ? '#fff' : 'var(--bg-soft)',
        fontSize: 13,
      }}>
        <span className={mono ? 'mono' : ''} style={{ color: value ? 'var(--ink)' : 'var(--ink-dim)' }}>
          {value || placeholder}
        </span>
      </div>
      {hint && <div style={{ marginTop: 5, fontSize: 11, color: 'var(--ink-mute)' }}>{hint}</div>}
    </div>
  );
}

Object.assign(window, {
  CBAMSidebar, KPI, SogliaBar, Donut, Bars, DeclLine, SimField, FormulaTable,
  IconGrid, IconDoc, IconCalc, IconUsers, IconGear, IconUpload,
  IconPlus, IconCheck, IconCheckCircle, IconInfo, IconAlert,
  IconChevron, IconArrowRight, IconFile, IconLock, IconEuro,
});

// ─── Formula audit table (replica of "Dettaglio formula — salvato per audit") ──
function FormulaTable({ compact = false, highlight = true } = {}) {
  const rows = [
    ['Anno di riferimento', '2026', ''],
    ['Modalità calcolo', 'Valori default', ''],
    ['Quantità merce', '2,603', 't'],
    ['Emissioni specifiche prodotto', '3,485664', 'tCO₂/t'],
    ['Benchmark CBAM (base riduzione ETS)', '1,397', 'tCO₂/t'],
    ['Fattore di riduzione', '97.5%', ''],
    ['Riduzione ETS (benchmark × fattore)', '1,362075', 'tCO₂/t'],
    ['Carbon price pagata paese terzo', '0,00', 'EUR/tCO₂'],
    ['Emissioni specifiche nette', '2,123589', 'tCO₂/t'],
    ['Emissioni incorporate (nette × quantità)', '5,527702', 'tCO₂'],
    ['Certificati richiesti', '6', 'cert.'],
    ['Prezzo certificato', '75,36', 'EUR/cert.'],
  ];
  return (
    <div style={{
      background: '#fff', border: '1px solid var(--line)', borderRadius: 12,
      boxShadow: 'var(--shadow-sm)', overflow: 'hidden', display: 'flex', flexDirection: 'column',
    }}>
      <div style={{
        padding: '12px 18px', background: 'var(--bg-soft)', borderBottom: '1px solid var(--line)',
        display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: 'var(--ink-soft)',
      }}>
        <IconInfo size={13} color="var(--ink-mute)"/>
        <span>Dettaglio formula — salvato per audit</span>
      </div>
      <div style={{ flex: 1, padding: compact ? '2px 0' : '4px 0' }}>
        {rows.map(([l, v, u], i) => (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '1fr auto 64px',
            padding: compact ? '7px 18px' : '9px 18px', gap: 16, alignItems: 'baseline',
            background: i % 2 === 1 ? 'var(--bg-soft)' : 'transparent',
            fontSize: compact ? 12 : 12.5,
          }}>
            <span style={{ color: 'var(--ink-soft)' }}>{l}</span>
            <span className="mono" style={{ color: 'var(--ink)', textAlign: 'right' }}>{v}</span>
            <span className="mono" style={{ color: 'var(--ink-mute)', textAlign: 'left' }}>{u}</span>
          </div>
        ))}
      </div>
      <div style={{
        padding: '14px 18px',
        background: highlight ? 'var(--accent-bg)' : 'var(--bg-soft)',
        borderTop: `1px solid ${highlight ? 'var(--teal-200)' : 'var(--line)'}`,
        display: 'grid', gridTemplateColumns: '1fr auto 64px',
        gap: 16, alignItems: 'baseline',
      }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: highlight ? 'var(--accent-ink)' : 'var(--ink)' }}>Costo stimato</span>
        <span className="num" style={{ fontSize: 22, color: 'var(--ink)', textAlign: 'right' }}>452,16</span>
        <span className="mono" style={{ fontSize: 11, color: 'var(--ink-mute)' }}>EUR</span>
      </div>
    </div>
  );
}
