// Shared chrome + primitives that replicate the real Gajo app UI
const ars = (n, dec) => '$' + n.toLocaleString('es-AR', { minimumFractionDigits: dec || 0, maximumFractionDigits: dec || 0 });

// Semáforo del sistema: ✅ ≤30% · ⚠️ 31-35% · ❌ >35%
const semaforo = (pct) => {
  if (pct <= 30) return { tone: 'good', color: 'var(--good)', bg: 'var(--good-tint)', label: 'OK' };
  if (pct <= 35) return { tone: 'warn', color: 'var(--warn)', bg: 'var(--warn-tint)', label: 'Atención' };
  return { tone: 'bad', color: 'var(--bad)', bg: 'var(--bad-tint)', label: 'Fuera' };
};

const NAV_GROUPS = [
  { label: null, items: [{ name: 'Inicio', icon: 'Home' }] },
  { label: 'Compras', items: [{ name: 'Órdenes de Compra', icon: 'Cart' }, { name: 'Facturas', icon: 'Doc' }, { name: 'Insumos', icon: 'Box' }] },
  { label: 'Cocina', items: [{ name: 'Elaboraciones', icon: 'Book' }, { name: 'Recetas', icon: 'Chef' }, { name: 'Carta', icon: 'Clipboard' }] },
  { label: 'Barra', items: [{ name: 'Vinos', icon: 'Wine' }, { name: 'Tragos', icon: 'Cocktail' }] },
  { label: 'Operación', items: [{ name: 'Ventas', icon: 'Dollar' }, { name: 'Análisis', icon: 'Trend' }, { name: 'Inventario', icon: 'Archive' }] },
  { label: 'Informes', items: [{ name: 'Estadísticas', icon: 'Bars' }] },
  { label: null, items: [{ name: 'Papelera', icon: 'Trash', badge: 6 }] },
];

// Compact replica of the product's dark-green sidebar
const AppSidebar = ({ active, compact }) => (
  <aside style={{
    background: 'var(--primary)',
    color: '#fff',
    padding: compact ? '14px 0' : '18px 0',
    width: compact ? 148 : 186,
    flexShrink: 0,
    display: 'flex',
    flexDirection: 'column',
    fontSize: compact ? 10.5 : 12,
  }}>
    <div style={{ padding: compact ? '0 12px 12px' : '0 16px 16px' }}>
      <div style={{ fontFamily: 'var(--serif)', fontSize: compact ? 15 : 18, lineHeight: 1 }}>{BRAND.name}</div>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 8.5, color: 'rgba(255,255,255,.45)', marginTop: 4 }}>v.43 · 20/08/26</div>
    </div>
    <div style={{ borderTop: '1px solid rgba(255,255,255,.10)', paddingTop: 8, display: 'flex', flexDirection: 'column', gap: 1, overflow: 'hidden' }}>
      {NAV_GROUPS.map((g, gi) => (
        <React.Fragment key={gi}>
          {g.label && (
            <div style={{
              fontFamily: 'var(--mono)', fontSize: 8, letterSpacing: '.12em', textTransform: 'uppercase',
              color: 'rgba(255,255,255,.38)', padding: compact ? '8px 12px 3px' : '10px 16px 4px',
            }}>{g.label}</div>
          )}
          {g.items.map(it => {
            const on = it.name === active;
            return (
              <div key={it.name} style={{
                display: 'flex', alignItems: 'center', gap: 8,
                padding: compact ? '5px 12px' : '6px 16px',
                margin: '0 6px', borderRadius: 6,
                background: on ? 'rgba(255,255,255,.11)' : 'transparent',
                color: on ? '#fff' : 'rgba(255,255,255,.72)',
                fontWeight: on ? 500 : 400,
                whiteSpace: 'nowrap',
              }}>
                <span style={{ opacity: .8, display: 'inline-flex' }}>{React.createElement(Icon[it.icon] || Icon.Box, { size: compact ? 11 : 13 })}</span>
                {it.name}
                {it.badge && <span style={{
                  marginLeft: 'auto', background: 'var(--accent)', color: '#fff',
                  fontFamily: 'var(--mono)', fontSize: 8, borderRadius: 999, padding: '0 4px',
                }}>{it.badge}</span>}
              </div>
            );
          })}
        </React.Fragment>
      ))}
    </div>
    <div style={{ marginTop: 'auto', paddingTop: 14, display: 'flex', alignItems: 'center', gap: 8, padding: compact ? '14px 12px 0' : '14px 16px 0' }}>
      <div style={{
        width: compact ? 20 : 24, height: compact ? 20 : 24, borderRadius: '50%',
        background: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 9, fontWeight: 600,
      }}>F</div>
      <div style={{ lineHeight: 1.2 }}>
        <div style={{ fontSize: compact ? 10 : 11.5, fontWeight: 500 }}>Francisco</div>
        <div style={{ fontSize: 8.5, color: 'rgba(255,255,255,.5)' }}>Admin</div>
      </div>
    </div>
  </aside>
);

// Escala un mockup denso para que entre completo en pantallas angostas
const ScaleToFit = ({ design = 620, children }) => {
  const outer = React.useRef(null), inner = React.useRef(null);
  const [k, setK] = React.useState(1), [h, setH] = React.useState(null);
  React.useEffect(() => {
    const calc = () => {
      if (!outer.current || !inner.current) return;
      const s = Math.min(1, outer.current.clientWidth / design);
      setK(s);
      setH(inner.current.offsetHeight * s);
    };
    calc();
    const ro = new ResizeObserver(calc);
    ro.observe(outer.current);
    ro.observe(inner.current);
    return () => ro.disconnect();
  }, [design]);
  return (
    <div ref={outer} style={{ width: '100%', height: h == null ? undefined : h, overflow: 'hidden' }}>
      <div ref={inner} style={{ width: design, transform: `scale(${k})`, transformOrigin: 'top left' }}>{children}</div>
    </div>
  );
};

// Browser-ish window that wraps a mockup
const AppWindow = ({ children, path, live, style, design }) => (
  <div style={{
    background: 'var(--bg-card)',
    border: '1px solid var(--line)',
    borderRadius: 'var(--radius-lg)',
    boxShadow: 'var(--shadow-lg)',
    overflow: 'hidden',
    ...style,
  }}>
    <div style={{
      padding: '9px 14px', borderBottom: '1px solid var(--line)',
      display: 'flex', alignItems: 'center', gap: 8, background: 'var(--bg-soft)',
    }}>
      <div style={{ display: 'flex', gap: 5 }}>
        {['#E5A0A0', '#E8CE9A', '#A5C8B0'].map(c => (
          <div key={c} style={{ width: 9, height: 9, borderRadius: '50%', background: c }}/>
        ))}
      </div>
      <div style={{ flex: 1, textAlign: 'center', fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--ink-muted)' }}>{path}</div>
      {live && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--ink-muted)' }}>
          <span className="pulse-dot" style={{ width: 5, height: 5 }}/>EN VIVO
        </div>
      )}
    </div>
    {design === false ? children : <ScaleToFit design={design || 620}>{children}</ScaleToFit>}
  </div>
);

// The product's page header: serif title + gray subtitle
const PageHead = ({ title, sub, right, size }) => (
  <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, marginBottom: 16 }}>
    <div>
      <div style={{ fontFamily: 'var(--serif)', fontSize: size || 26, lineHeight: 1.05 }}>{title}</div>
      {sub && <div style={{ fontSize: 11.5, color: 'var(--ink-muted)', marginTop: 3 }}>{sub}</div>}
    </div>
    {right}
  </div>
);

// KPI card exactly like the product's dashboard tiles
const KpiCard = ({ label, value, delta, deltaTone, note, highlight, mono }) => (
  <div style={{
    padding: '13px 15px',
    background: highlight ? 'var(--good-tint)' : 'var(--bg-card)',
    border: '1px solid ' + (highlight ? '#BFDECB' : 'var(--line)'),
    borderRadius: 10,
  }}>
    <div style={{
      fontFamily: 'var(--mono)', fontSize: 8.5, letterSpacing: '.1em',
      textTransform: 'uppercase', color: highlight ? 'var(--good)' : 'var(--ink-muted)', marginBottom: 6,
    }}>{label}</div>
    <div className="ticker" style={{
      fontFamily: mono === false ? 'var(--serif)' : 'var(--mono)',
      fontSize: mono === false ? 24 : 21, fontWeight: mono === false ? 400 : 500,
      lineHeight: 1, color: highlight ? 'var(--good)' : 'var(--ink)',
    }}>{value}</div>
    {delta && (
      <div style={{
        fontFamily: 'var(--mono)', fontSize: 9.5, marginTop: 5,
        color: deltaTone === 'bad' ? 'var(--bad)' : deltaTone === 'good' ? 'var(--good)' : 'var(--ink-muted)',
      }}>{delta}</div>
    )}
    {note && <div style={{ fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--ink-muted)', marginTop: 4 }}>{note}</div>}
  </div>
);

// FC pill with the product's semáforo colors
const FcPill = ({ pct, showIcon }) => {
  const s = semaforo(pct);
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      padding: '2px 7px', borderRadius: 5, background: s.bg, color: s.color,
      fontFamily: 'var(--mono)', fontSize: 10.5, fontWeight: 500,
    }}>
      {showIcon !== false && <span style={{ fontSize: 9 }}>{s.tone === 'good' ? '✓' : s.tone === 'warn' ? '!' : '×'}</span>}
      {pct.toFixed(1)}%
    </span>
  );
};

const Toggle = ({ on }) => (
  <div style={{
    width: 26, height: 15, borderRadius: 999, padding: 2,
    background: on ? 'var(--good)' : 'var(--line-strong)',
    display: 'flex', justifyContent: on ? 'flex-end' : 'flex-start',
    transition: 'background 200ms ease',
  }}>
    <div style={{ width: 11, height: 11, borderRadius: '50%', background: '#fff' }}/>
  </div>
);

// Donut used for "Composición del costo"
const Donut = ({ slices, size, thickness }) => {
  const S = size || 96, T = thickness || 15, R = (S - T) / 2, C = 2 * Math.PI * R;
  let acc = 0;
  return (
    <svg width={S} height={S} viewBox={`0 0 ${S} ${S}`} style={{ transform: 'rotate(-90deg)' }}>
      {slices.map((s, i) => {
        const len = (s.pct / 100) * C, off = acc;
        acc += len;
        return (
          <circle key={i} cx={S/2} cy={S/2} r={R} fill="none"
            stroke={s.color} strokeWidth={T}
            strokeDasharray={`${len} ${C - len}`} strokeDashoffset={-off}
            style={{ transition: 'stroke-dasharray 400ms ease, stroke-dashoffset 400ms ease' }}/>
        );
      })}
    </svg>
  );
};

const SectionHead = ({ eyebrow, title, blurb, center, maxWidth }) => (
  <div style={{
    maxWidth: maxWidth || 760, marginBottom: 56,
    textAlign: center ? 'center' : 'left',
    marginLeft: center ? 'auto' : 0, marginRight: center ? 'auto' : 0,
  }}>
    <div className="eyebrow" style={{ marginBottom: 16 }}>{eyebrow}</div>
    <h2 className="display" style={{ fontSize: 'clamp(34px, 4.4vw, 54px)', margin: '0 0 20px' }}>{title}</h2>
    {blurb && <p className="body-lg">{blurb}</p>}
  </div>
);

Object.assign(window, { ars, semaforo, NAV_GROUPS, AppSidebar, AppWindow, ScaleToFit, PageHead, KpiCard, FcPill, Toggle, Donut, SectionHead });
