// Shared chrome: status bar, page header, tab bar, sparkline, etc.
// Everything here uses CSS custom-property tokens so tenant/theme flips work.

function StatusBar() {
  return (
    <div className="ib-row" style={{ justifyContent: 'space-between', padding: '14px 22px 4px', fontSize: 14, fontWeight: 600, color: 'var(--ink)', fontVariantNumeric: 'tabular-nums' }}>
      <span>9:41</span>
      <span style={{ display: 'flex', gap: 5, alignItems: 'center' }}>
        <svg width="18" height="10" viewBox="0 0 18 10" fill="currentColor"><rect x="0" y="6" width="3" height="4"/><rect x="4" y="4" width="3" height="6"/><rect x="8" y="2" width="3" height="8"/><rect x="12" y="0" width="3" height="10"/></svg>
        <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" strokeWidth="1.2"><path d="M1 4 a8 8 0 0 1 12 0 M3 6 a5 5 0 0 1 8 0"/><circle cx="7" cy="9" r="1" fill="currentColor"/></svg>
        <svg width="22" height="10" viewBox="0 0 22 10" fill="none" stroke="currentColor" strokeWidth="1"><rect x="0.5" y="0.5" width="18" height="9" rx="1.5"/><rect x="2" y="2" width="14" height="6" fill="currentColor"/><rect x="19.5" y="3.5" width="1.5" height="3" fill="currentColor"/></svg>
      </span>
    </div>
  );
}

// Wordmark — small, mono, with file-id-style metadata. From B's spine.
function PageChrome({ section, fileId, right, embed }) {
  if (embed) return null;
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', padding: '4px 22px 12px', borderBottom: '1px solid var(--rule)' }}>
      <div className="ib-row ib-gap-m" style={{ alignItems: 'baseline' }}>
        <span className="ib-mono" style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', color: 'var(--ink)' }}>
          <span style={{ color: 'var(--accent)' }}>●</span> <TenantWordmark/>
        </span>
        {section && <span className="ib-eyebrow" style={{ fontSize: 9 }}>{section}</span>}
      </div>
      {right || (fileId && <span className="ib-mono" style={{ fontSize: 9, color: 'var(--ink-mute)', letterSpacing: '0.06em' }}>{fileId}</span>)}
    </div>
  );
}

function TenantWordmark() {
  // Pull from CSS variable so the wordmark text follows tenant attribute.
  const [name, setName] = React.useState('');
  React.useEffect(() => {
    const v = getComputedStyle(document.documentElement).getPropertyValue('--tenant-name').trim().replace(/^"|"$/g, '');
    setName(v || 'Core Gym Club');
    const obs = new MutationObserver(() => {
      const v2 = getComputedStyle(document.documentElement).getPropertyValue('--tenant-name').trim().replace(/^"|"$/g, '');
      setName(v2 || 'Core Gym Club');
    });
    obs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-tenant', 'data-theme'] });
    return () => obs.disconnect();
  }, []);
  return <span>{name}</span>;
}

// Bottom tab bar
function TabBar({ active, onNav, embed }) {
  if (embed) return null;
  const tabs = [
    { id: 'scan',    label: 'Skanna' },
    { id: 'history', label: 'Utveckling' },
    { id: 'data',    label: 'Mitt arkiv' },
  ];
  return (
    <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, borderTop: '1px solid var(--rule)', background: 'var(--paper)', display: 'flex' }}>
      {tabs.map((t, i) => (
        <button key={t.id} onClick={() => onNav && onNav(t.id)} style={{ flex: 1, padding: '14px 0 30px', textAlign: 'center', background: 'transparent', border: 'none', borderRight: i < tabs.length - 1 ? '1px solid var(--rule-soft)' : 'none', cursor: 'pointer', fontFamily: 'var(--mono)', fontSize: 10, fontWeight: 500, letterSpacing: '0.1em', color: t.id === active ? 'var(--ink)' : 'var(--ink-mute)', textTransform: 'uppercase' }}>
          <span style={{ color: t.id === active ? 'var(--accent)' : 'var(--ink-faint)', marginRight: 6, fontWeight: 700 }}>{String(i+1).padStart(2,'0')}</span>{t.label}
        </button>
      ))}
    </div>
  );
}

// Sparkline — used on history grid + recent scan
function Sparkline({ values, width = 120, height = 28, accent, area = false }) {
  if (!values || values.length < 2) return <svg width={width} height={height} />;
  const min = Math.min(...values);
  const max = Math.max(...values);
  const range = max - min || 1;
  const stepX = width / (values.length - 1);
  const pts = values.map((v, i) => `${i * stepX},${(height - ((v - min) / range) * (height - 4) - 2).toFixed(2)}`);
  const last = pts[pts.length - 1].split(',').map(Number);
  const color = accent || 'var(--ink)';
  return (
    <svg width={width} height={height} style={{ display: 'block', overflow: 'visible' }}>
      {area && <polyline points={[...pts, `${width},${height}`, `0,${height}`].join(' ')} fill={color} fillOpacity="0.08" stroke="none" />}
      <line x1="0" y1="0.5" x2={width} y2="0.5" stroke="var(--rule-hair)" strokeWidth="0.5" strokeDasharray="2 2"/>
      <line x1="0" y1={height-0.5} x2={width} y2={height-0.5} stroke="var(--rule-hair)" strokeWidth="0.5" strokeDasharray="2 2"/>
      <polyline points={pts.join(' ')} fill="none" stroke={color} strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={last[0]} cy={last[1]} r="2.4" fill={color} />
    </svg>
  );
}

// Editorial title block — eyebrow + serif heading
function TitleBlock({ eyebrow, title, sub, num }) {
  return (
    <div style={{ padding: '24px 22px 18px' }}>
      {eyebrow && <div className="ib-eyebrow" style={{ marginBottom: 12 }}>
        {num && <span className="ib-eyebrow-num">{num}</span>}{eyebrow}
      </div>}
      <h1 className="ib-h1" style={{ fontSize: 28, margin: 0, marginBottom: sub ? 8 : 0, color: 'var(--ink)' }}>{title}</h1>
      {sub && <p style={{ fontFamily: 'var(--sans)', fontSize: 13, lineHeight: 1.5, color: 'var(--ink-soft)', margin: 0, marginTop: 10 }}>{sub}</p>}
    </div>
  );
}

// Numbered §-paragraph block — B's contribution
function ClauseBlock({ items }) {
  return (
    <div className="ib-rule" style={{ borderTop: '1px solid var(--rule)' }}>
      {items.map(([n, k, v], i) => (
        <div key={n} style={{ display: 'grid', gridTemplateColumns: '36px 1fr', gap: 8, padding: '14px 22px', borderBottom: i < items.length - 1 ? '1px solid var(--rule-soft)' : '1px solid var(--rule)', alignItems: 'flex-start' }}>
          <span className="ib-mono" style={{ fontSize: 11, fontWeight: 700, color: 'var(--accent)', lineHeight: 1.6 }}>{n}</span>
          <div>
            <div className="ib-eyebrow" style={{ marginBottom: 4 }}>{k}</div>
            <div className="ib-serif" style={{ fontSize: 14, lineHeight: 1.45, color: 'var(--ink)' }}>{v}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

// Data row — used on every scan-detail / resultat table
function DataRow({ label, value, unit, uncertain, missing, secondary, prefix }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '14px 1fr auto 56px', gap: 8, padding: '11px 22px', borderBottom: '1px solid var(--rule-soft)', alignItems: 'baseline' }}>
      <span className="ib-mono" style={{ fontSize: 9, color: uncertain ? 'var(--warn)' : 'var(--ink-faint)', fontWeight: 700 }}>{prefix || '·'}</span>
      <span style={{ fontSize: 13, color: 'var(--ink)', fontWeight: 500 }}>
        {label}
        {uncertain && <span className="ib-tag ib-tag-warn" style={{ marginLeft: 8 }}>OSÄKER</span>}
        {secondary && <span className="ib-mono" style={{ fontSize: 10, color: 'var(--ink-mute)', marginLeft: 8 }}>{secondary}</span>}
      </span>
      <span className="ib-num ib-serif" style={{ fontSize: 20, fontWeight: 400, color: missing ? 'var(--ink-faint)' : 'var(--ink)' }}>{missing ? '—' : value}</span>
      <span className="ib-mono" style={{ fontSize: 10, color: 'var(--ink-mute)', textAlign: 'right' }}>{unit || ''}</span>
    </div>
  );
}

// Section header — small eyebrow with rule above the data block
function SectionHead({ num, title, right }) {
  return (
    <div style={{ padding: '20px 22px 8px', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', borderTop: '1px solid var(--rule)', marginTop: -1 }}>
      <span className="ib-eyebrow"><span className="ib-eyebrow-num">{num}</span>{title}</span>
      {right}
    </div>
  );
}

// iPhone-frame for desktop preview. Mobile-first; on real phones we go full-bleed.
function PhoneFrame({ children, w = 390, h = 844 }) {
  return (
    <div style={{ width: w, height: h, background: 'var(--paper)', position: 'relative', overflow: 'hidden', borderRadius: 0, boxShadow: '0 30px 80px rgba(40,30,20,0.15), 0 8px 24px rgba(40,30,20,0.08)' }}>
      {children}
    </div>
  );
}

Object.assign(window, {
  StatusBar, PageChrome, TabBar, Sparkline, TitleBlock, ClauseBlock, DataRow, SectionHead, PhoneFrame, TenantWordmark
});
