/* Product panels for the nine module cards — soft, rounded, one headline
   figure per card, then a single visual of the underlying data. */

const pnCard = '#151515';
const pnInset = '#1f1f1f';
const pnTrack = 'rgba(233,226,210,0.1)';
const pnSans = { fontFamily: 'var(--font-body)', fontVariantNumeric: 'tabular-nums' };
const pnCap = { ...pnSans, fontSize: '13px', lineHeight: 1.3, color: 'var(--k-bone-faint)', letterSpacing: '-0.005em' };
const pnText = { ...pnSans, fontSize: '15px', lineHeight: 1.35, color: 'var(--k-bone)', letterSpacing: '-0.01em' };

function PnIcon({ name, size = 14, color }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (ref.current && window.lucide) {
      ref.current.innerHTML = '<i data-lucide="' + name + '"></i>';
      window.lucide.createIcons({ attrs: { 'stroke-width': 2, width: size, height: size } });
    }
  }, [name, size]);
  return <span ref={ref} aria-hidden="true" style={{ display: 'inline-flex', color, flex: 'none' }} />;
}

function PnShell({ label, status, children }) {
  return (
    <div data-count style={{ background: pnCard, borderRadius: '28px', border: '1px solid rgba(255,255,255,0.06)', padding: '26px 26px 28px', display: 'grid', gap: '22px', alignContent: 'start', height: '100%', boxSizing: 'border-box', overflow: 'hidden' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '12px' }}>
        <span style={{ ...pnCap, fontWeight: 500 }}>{label}</span>
        {status && <span style={{ ...pnSans, fontSize: '12px', fontWeight: 500, color: 'var(--k-lime)', background: 'rgba(190,242,100,0.12)', borderRadius: '999px', padding: '5px 10px', display: 'inline-flex', alignItems: 'center', gap: '6px', whiteSpace: 'nowrap' }}>
          <span style={{ width: '6px', height: '6px', background: 'var(--k-lime)', borderRadius: '50%' }}></span>{status}
        </span>}
      </div>
      {children}
    </div>
  );
}

function PnHead({ value, tone, sub }) {
  const c = tone === 'lime' ? 'var(--k-lime)' : tone === 'orange' ? 'var(--k-orange)' : 'var(--k-bone)';
  return (
    <div style={{ display: 'grid', gap: '6px' }}>
      <span style={{ ...pnSans, fontSize: 'clamp(2.25rem, 3.4vw, 3rem)', fontWeight: 600, letterSpacing: '-0.035em', lineHeight: 1, color: c }}>{value}</span>
      {sub && <span style={{ ...pnCap, fontSize: '14px', color: 'var(--k-bone-dim)' }}>{sub}</span>}
    </div>
  );
}

function PnInset({ children, pad = '6px 16px' }) {
  return <div style={{ background: pnInset, borderRadius: '18px', padding: pad, display: 'grid' }}>{children}</div>;
}

function PnRow({ children, last, cols = 'minmax(0,1fr) auto' }) {
  return <div style={{ display: 'grid', gridTemplateColumns: cols, gap: '12px', alignItems: 'center', padding: '11px 0', borderBottom: last ? 'none' : '1px solid rgba(255,255,255,0.06)' }}>{children}</div>;
}

/* 01 */
function RecipeSheet() {
  const lines = [['Trout fillet', '180 g', 4.32], ['Crème fraîche', '30 g', 0.54], ['Dill', '12 g', 0.38], ['Rye crumb', '40 g', 0.21]];
  const total = 5.45;
  const tones = ['var(--k-orange)', 'var(--k-bone)', 'var(--k-bone-dim)', 'var(--k-bone-faint)'];
  return (
    <PnShell label="Recipe Bible · plate 048" status="Auto-costed">
      <div style={{ display: 'grid', gap: '14px' }}>
        <span style={{ ...pnText, fontSize: '19px', fontWeight: 600 }}>Cured trout, dill oil, rye</span>
        <PnHead value="22.7%" tone="lime" sub="Food cost · €5.45 plate · €24.00 menu" />
      </div>
      <div data-bar style={{ display: 'flex', height: '12px', gap: '3px' }}>
        {lines.map(([n, , c], i) => <div key={n} style={{ width: (c / total) * 100 + '%', background: tones[i], borderRadius: '999px' }}></div>)}
      </div>
      <PnInset>
        {lines.map(([n, g, c], i) => (
          <PnRow key={n} last={i === lines.length - 1} cols="10px minmax(0,1fr) auto auto">
            <span style={{ width: '10px', height: '10px', borderRadius: '50%', background: tones[i] }}></span>
            <span style={pnText}>{n}</span>
            <span style={pnCap}>{g}</span>
            <span style={{ ...pnText, fontWeight: 500, minWidth: '3.5rem', textAlign: 'right' }}>€{c.toFixed(2)}</span>
          </PnRow>
        ))}
      </PnInset>
    </PnShell>
  );
}

/* 02 */
function AgentThread() {
  const wave = [4, 7, 10, 6, 12, 16, 9, 13, 18, 11, 7, 14, 10, 17, 12, 8, 13, 6, 10, 15, 9, 5, 11, 7, 4];
  const steps = [['Recipe written to the Bible', 'plate 048'], ['4 ingredients matched to stock', '100%'], ['Costed', '€5.45 / plate'], ['Reserved for service', '4 covers']];
  return (
    <PnShell label="Chef Agent" status="Listening">
      <div style={{ background: pnInset, borderRadius: '22px 22px 22px 6px', padding: '16px 18px', display: 'grid', gap: '12px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          <span style={{ width: '32px', height: '32px', borderRadius: '50%', background: 'var(--k-orange)', color: 'var(--k-black)', display: 'grid', placeItems: 'center', flex: 'none' }}><PnIcon name="mic" size={15} /></span>
          <div aria-hidden="true" style={{ display: 'flex', alignItems: 'center', gap: '3px', height: '20px', flex: 1, minWidth: 0, overflow: 'hidden' }}>
            {wave.map((h, i) => <span key={i} style={{ width: '3px', flex: 'none', height: h + 'px', borderRadius: '2px', background: 'var(--k-orange)' }}></span>)}
          </div>
        </div>
        <p style={{ ...pnText, fontSize: '16px', margin: 0 }}>“Truta curada com óleo de endro e crocante de centeio — quatro doses.”</p>
      </div>
      <PnInset>
        {steps.map(([k, v], i) => (
          <PnRow key={k} last={i === steps.length - 1} cols="auto minmax(0,1fr) auto">
            <span style={{ width: '20px', height: '20px', borderRadius: '50%', background: 'var(--k-lime)', color: 'var(--k-black)', display: 'grid', placeItems: 'center' }}><PnIcon name="check" size={12} /></span>
            <span style={pnText}>{k}</span>
            <span style={{ ...pnCap, color: 'var(--k-bone-dim)', whiteSpace: 'nowrap' }}>{v}</span>
          </PnRow>
        ))}
      </PnInset>
      <div style={{ display: 'flex', gap: '10px', alignItems: 'center', padding: '12px 16px', borderRadius: '16px', background: 'rgba(255,106,26,0.12)', color: 'var(--k-orange)' }}>
        <PnIcon name="triangle-alert" size={15} />
        <span style={{ ...pnSans, fontSize: '14px', lineHeight: 1.35 }}>Dill below par — 48 g needed, 40 g on hand</span>
      </div>
    </PnShell>
  );
}

/* 03 */
function StockLedger() {
  const rows = [['Trout fillet', 3.2, 5.0, 'kg'], ['Rye flour', 8.4, 6.0, 'kg'], ['Crème fraîche', 2.1, 2.0, 'L'], ['Dill', 0.04, 0.25, 'kg']];
  return (
    <PnShell label="Inventory · live" status="Synced 2 min">
      <PnHead value="2 below par" tone="orange" sub="Draft PO ready for Hortas do Tejo" />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0,1fr))', gap: '10px' }}>
        {rows.map(([name, have, par, unit]) => {
          const scale = Math.max(have, par) * 1.15;
          const low = have < par;
          return (
            <div key={name} style={{ display: 'grid', gap: '10px' }}>
              <div style={{ position: 'relative', height: '8.5rem', background: pnInset, borderRadius: '14px', overflow: 'hidden' }}>
                <div style={{ position: 'absolute', left: '5px', right: '5px', bottom: '5px', height: 'calc(' + Math.max(3, (have / scale) * 100) + '% - 10px)', minHeight: '6px', background: low ? 'var(--k-orange)' : 'var(--k-lime)', borderRadius: '10px' }}></div>
                <div style={{ position: 'absolute', left: 0, right: 0, bottom: (par / scale) * 100 + '%', height: '2px', background: 'var(--k-bone)', opacity: 0.7 }}></div>
              </div>
              <div style={{ display: 'grid', gap: '2px' }}>
                <span style={{ ...pnText, fontSize: '14px', fontWeight: 600, color: low ? 'var(--k-orange)' : 'var(--k-bone)' }}>{have} {unit}</span>
                <span style={{ ...pnCap, fontSize: '12px' }}>{name}</span>
              </div>
            </div>
          );
        })}
      </div>
    </PnShell>
  );
}

/* 04 */
function SalesReadout() {
  const rows = [['Cured trout', '€24', 77, 'up'], ['Aged beef, cep', '€38', 61, 'flat'], ['Cod, brassicas', '€26', 58, 'down']];
  const arrow = { up: 'arrow-up-right', flat: 'arrow-right', down: 'arrow-down-right' };
  return (
    <PnShell label="Sales Intelligence · 5 agents" status="Weekly run">
      <span style={{ ...pnSans, fontSize: 'clamp(1.5rem, 2.2vw, 1.9rem)', fontWeight: 600, letterSpacing: '-0.03em', lineHeight: 1.1, color: 'var(--k-bone)' }}>Rest the cod. Run trout through October.</span>
      <PnInset pad="18px 16px">
        <div style={{ display: 'grid', gap: '16px' }}>
          {rows.map(([dish, price, m, dir]) => {
            const c = dir === 'down' ? 'var(--k-orange)' : 'var(--k-lime)';
            return (
              <div key={dish} style={{ display: 'grid', gap: '8px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: '12px' }}>
                  <span style={pnText}>{dish} <span style={pnCap}>{price}</span></span>
                  <span style={{ ...pnText, fontWeight: 600, color: c, display: 'inline-flex', alignItems: 'center', gap: '4px' }}>{m}%<PnIcon name={arrow[dir]} size={14} /></span>
                </div>
                <div style={{ height: '8px', background: pnTrack, borderRadius: '999px', overflow: 'hidden' }}><div data-bar style={{ height: '100%', width: m + '%', background: c, borderRadius: '999px' }}></div></div>
              </div>
            );
          })}
        </div>
      </PnInset>
      <span style={pnCap}>Margin per dish</span>
    </PnShell>
  );
}

/* 05 */
function ResearchFeed() {
  const months = ['Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  const rows = [['Black truffle', 'Local', 3, 6, true], ['Wild mushrooms', 'Local', 2, 5, true], ['Heirloom tomato', 'Import', 0, 4, true], ['San Marzano', 'Campania', 0, 6, false], ['Burrata', 'Campania', 0, 6, false]];
  return (
    <PnShell label="AI Research · sourcing" status="12 sources read">
      <PnHead value="3 confirmed" tone="lime" sub="For the autumn menu · 2 held for price" />
      <PnInset pad="14px 14px 16px">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, minmax(0,1fr))', gap: '4px', marginBottom: '10px' }}>
          {months.map((m, i) => <span key={m} style={{ ...pnCap, fontSize: '11px', textAlign: 'center', color: i >= 3 ? 'var(--k-bone)' : 'var(--k-bone-faint)' }}>{m}</span>)}
        </div>
        <div style={{ display: 'grid', gap: '8px' }}>
          {rows.map(([name, origin, a, b, ok]) => (
            <div key={name} style={{ display: 'grid', gridTemplateColumns: 'repeat(6, minmax(0,1fr))', gap: '4px' }}>
              <div style={{ gridColumn: (a + 1) + ' / ' + (b + 1), borderRadius: '999px', padding: '6px 10px', background: ok ? 'var(--k-lime)' : 'transparent', border: ok ? '1px solid transparent' : '1px solid rgba(233,226,210,0.25)', color: ok ? 'var(--k-black)' : 'var(--k-bone-dim)', display: 'flex', justifyContent: 'space-between', gap: '8px', minWidth: 0 }}>
                <span style={{ ...pnSans, fontSize: '12px', fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{name}</span>
                <span style={{ ...pnSans, fontSize: '11px', opacity: 0.7, whiteSpace: 'nowrap' }}>{origin}</span>
              </div>
            </div>
          ))}
        </div>
      </PnInset>
    </PnShell>
  );
}

/* 06 */
function SupplierMatch() {
  const groups = [
    ['Tartufi Italia', [['Black truffle 30 g', '€41.00', true]]],
    ['Hortas do Tejo', [['Wild mushrooms 2 kg', '€28.40', true], ['Heirloom tomato 4 kg', '€19.20', true]]],
    ['Casa Marzano', [['San Marzano D.O.P. 12 tin', '€34.80', false]]],
  ];
  return (
    <PnShell label="Suppliers · draft order" status="4 lines mapped">
      <PnHead value="€123.40" sub="Order total" />
      <div style={{ display: 'grid', gap: '12px' }}>
        {groups.map(([sup, lines]) => (
          <div key={sup} style={{ display: 'grid', gap: '6px' }}>
            <span style={{ ...pnCap, fontSize: '12px', paddingLeft: '16px' }}>{sup}</span>
            <PnInset>
              {lines.map(([line, price, ok], i) => (
                <PnRow key={line} last={i === lines.length - 1} cols="minmax(0,1fr) auto auto">
                  <span style={pnText}>{line}</span>
                  <span style={{ ...pnSans, fontSize: '11px', fontWeight: 600, borderRadius: '999px', padding: '3px 8px', background: ok ? 'rgba(190,242,100,0.14)' : 'rgba(255,106,26,0.14)', color: ok ? 'var(--k-lime)' : 'var(--k-orange)', whiteSpace: 'nowrap' }}>{ok ? 'Mapped' : 'New item'}</span>
                  <span style={{ ...pnText, fontWeight: 500, minWidth: '3.6rem', textAlign: 'right' }}>{price}</span>
                </PnRow>
              ))}
            </PnInset>
          </div>
        ))}
      </div>
    </PnShell>
  );
}

/* 07 */
function MenuComposer() {
  const rows = [['Tagliolini al tartufo', '€24', 26.1, 'Autumn'], ['Roasted wild mushrooms', '€18', 21.4, 'Autumn'], ['Heirloom tomato salad', '€16', 19.8, 'Late summer'], ['Handmade cappelletti', '€20', 23.0, 'Autumn'], ['Grilled seabass', '€26', 28.6, 'Year round']];
  const max = 32, target = 24;
  return (
    <PnShell label="Seasonal Menu · autumn draft" status="5 dishes costed">
      <PnHead value="23.8%" tone="lime" sub="Menu food cost · target 24%" />
      <PnInset>
        {rows.map(([dish, price, fc, tag], i) => {
          const over = fc > target;
          return (
            <div key={dish} style={{ display: 'grid', gap: '8px', padding: '12px 0', borderBottom: i === rows.length - 1 ? 'none' : '1px solid rgba(255,255,255,0.06)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: '12px' }}>
                <span style={{ ...pnText, minWidth: 0 }}>{dish} <span style={pnCap}>{price} · {tag}</span></span>
                <span style={{ ...pnText, fontWeight: 600, color: over ? 'var(--k-orange)' : 'var(--k-lime)' }}>{fc.toFixed(1)}%</span>
              </div>
              <div style={{ position: 'relative', height: '6px', background: pnTrack, borderRadius: '999px' }}>
                <div data-bar style={{ height: '100%', width: (fc / max) * 100 + '%', background: over ? 'var(--k-orange)' : 'var(--k-lime)', borderRadius: '999px' }}></div>
                <div style={{ position: 'absolute', top: '-4px', bottom: '-4px', left: (target / max) * 100 + '%', width: '2px', borderRadius: '1px', background: 'var(--k-bone)' }}></div>
              </div>
            </div>
          );
        })}
      </PnInset>
    </PnShell>
  );
}


/* Prepared Recipes — one batch, scaled, with steps */
function BatchSheet() {
  const lines = [['Veal bones, roasted', '5.0 kg', 11.50], ['Mirepoix', '1.2 kg', 2.16], ['Tomato paste', '150 g', 0.62], ['Red wine', '750 ml', 4.20]];
  const steps = [['Roast bones', '200°C · 45 min', true], ['Deglaze, reduce wine', '20 min', true], ['Simmer', '8 h', false], ['Strain, reduce to glace', '1.8 L yield', false]];
  return (
    <PnShell label="Prepared · jus de veau" status="Batch 12">
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0,1fr))', gap: '12px' }}>
        <PnHead value="1.8 L" sub="Yield · 36 portions" />
        <PnHead value="€0.51" tone="lime" sub="Per 50 ml portion" />
      </div>
      <PnInset>
        {lines.map(([n, q, c], i) => (
          <PnRow key={n} last={i === lines.length - 1} cols="minmax(0,1fr) auto auto">
            <span style={pnText}>{n}</span>
            <span style={pnCap}>{q}</span>
            <span style={{ ...pnText, fontWeight: 500, minWidth: '3.5rem', textAlign: 'right' }}>€{c.toFixed(2)}</span>
          </PnRow>
        ))}
      </PnInset>
      <div style={{ display: 'grid', gap: '10px' }}>
        {steps.map(([s, t, done], i) => (
          <div key={s} style={{ display: 'grid', gridTemplateColumns: '24px minmax(0,1fr) auto', gap: '12px', alignItems: 'center' }}>
            <span style={{ width: '24px', height: '24px', borderRadius: '50%', display: 'grid', placeItems: 'center', background: done ? 'var(--k-lime)' : pnInset, color: done ? 'var(--k-black)' : 'var(--k-bone-faint)', ...pnSans, fontSize: '12px', fontWeight: 600 }}>{done ? <PnIcon name="check" size={12} /> : i + 1}</span>
            <span style={{ ...pnText, color: done ? 'var(--k-bone-dim)' : 'var(--k-bone)' }}>{s}</span>
            <span style={pnCap}>{t}</span>
          </div>
        ))}
      </div>
    </PnShell>
  );
}

/* AI Analytics — margin trend with findings */
function AnalyticsTrend() {
  const pts = [64, 66, 63, 61, 62, 58, 57, 60, 63, 65, 67, 68];
  const w = 300, h = 90, min = 52, max = 72;
  const xy = pts.map((v, i) => [(i / (pts.length - 1)) * w, h - ((v - min) / (max - min)) * h]);
  const d = xy.map(([x, y], i) => (i ? 'L' : 'M') + x.toFixed(1) + ' ' + y.toFixed(1)).join(' ');
  const finds = [['Waste on fish up 18% on Mondays', 'orange', 'trending-up'], ['Aged beef margin recovered after supplier switch', 'lime', 'arrow-up-right'], ['Dessert attach rate falls after 22:00', 'orange', 'clock']];
  return (
    <PnShell label="AI Analytics · 12 weeks" status="Updated today">
      <PnHead value="68%" tone="lime" sub="Gross margin · +7 pts since week 7" />
      <PnInset pad="16px 16px 12px">
        <svg viewBox={'0 0 ' + w + ' ' + (h + 4)} preserveAspectRatio="none" style={{ width: '100%', height: '96px', display: 'block', overflow: 'visible' }} aria-hidden="true">
          <path d={d + ' L ' + w + ' ' + (h + 4) + ' L 0 ' + (h + 4) + ' Z'} fill="rgba(190,242,100,0.12)"></path>
          <path d={d} fill="none" stroke="var(--k-lime)" strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke"></path>
        </svg>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '8px' }}>
          <span style={{ ...pnCap, fontSize: '11px' }}>Wk 1</span><span style={{ ...pnCap, fontSize: '11px' }}>Wk 12</span>
        </div>
      </PnInset>
      <div style={{ display: 'grid', gap: '10px' }}>
        {finds.map(([t, tone, ic]) => (
          <div key={t} style={{ display: 'grid', gridTemplateColumns: '28px minmax(0,1fr)', gap: '12px', alignItems: 'center' }}>
            <span style={{ width: '28px', height: '28px', borderRadius: '50%', display: 'grid', placeItems: 'center', background: tone === 'lime' ? 'rgba(190,242,100,0.14)' : 'rgba(255,106,26,0.14)', color: tone === 'lime' ? 'var(--k-lime)' : 'var(--k-orange)' }}><PnIcon name={ic} size={14} /></span>
            <span style={pnText}>{t}</span>
          </div>
        ))}
      </div>
    </PnShell>
  );
}

Object.assign(window, { BatchSheet, AnalyticsTrend, RecipeSheet, AgentThread, StockLedger, SalesReadout, ResearchFeed, SupplierMatch, MenuComposer });
