// Shared UI primitives for Butterfly Coffee
// Elegant: forest green + serif display + sans body

const { useState, useEffect, useMemo, useRef } = React;

// --- Currency
const baht = (n) => `฿${Math.round(n).toLocaleString('th-TH')}`;
const bahtDecimal = (n) => `฿${n.toLocaleString('th-TH', { minimumFractionDigits: 0, maximumFractionDigits: 1 })}`;

// --- Tone -> CSS background for menu card placeholder
// We avoid SVG hand-drawn coffee, but give each drink a tasteful gradient
// that suggests its color personality. Striped placeholder texture.
const TONE_BG = {
  espresso:  'linear-gradient(135deg, #3a241a 0%, #1d120c 100%)',
  black:     'linear-gradient(135deg, #2a201a 0%, #0f0a07 100%)',
  milky:     'linear-gradient(135deg, #c8a87a 0%, #6b4a30 100%)',
  chocolate: 'linear-gradient(135deg, #4a2f22 0%, #1f130d 100%)',
  tea:       'linear-gradient(135deg, #c47a3a 0%, #7a3f1e 100%)',
  matcha:    'linear-gradient(135deg, #6b8a4a 0%, #2f4824 100%)',
  addon:     'linear-gradient(135deg, #ede5d3 0%, #c9bca0 100%)',
};

const TempBadge = ({ temp }) => {
  if (!temp) return null;
  const isHot = temp === 'hot';
  return (
    <span className="bf-temp" data-temp={temp}>
      {isHot ? 'HOT' : 'ICED'}
    </span>
  );
};

// --- Card with optional title bar
const Card = ({ title, subtitle, action, children, className = '', padding = true }) => (
  <section className={`bf-card ${className}`}>
    {(title || action) && (
      <header className="bf-card-head">
        <div>
          {title && <h3 className="bf-card-title">{title}</h3>}
          {subtitle && <p className="bf-card-sub">{subtitle}</p>}
        </div>
        {action}
      </header>
    )}
    <div className={`bf-card-body ${padding ? '' : 'bf-card-body-flush'}`}>{children}</div>
  </section>
);

// --- Stat
const Stat = ({ label, value, sub, delta, accent }) => (
  <div className="bf-stat" data-accent={accent || 'default'}>
    <div className="bf-stat-label">{label}</div>
    <div className="bf-stat-value">{value}</div>
    <div className="bf-stat-meta">
      {sub && <span className="bf-stat-sub">{sub}</span>}
      {delta !== undefined && delta !== null && (
        <span className={`bf-delta ${delta >= 0 ? 'pos' : 'neg'}`}>
          {delta >= 0 ? '▲' : '▼'} {Math.abs(delta).toFixed(0)}%
        </span>
      )}
    </div>
  </div>
);

// --- Pill button
const Pill = ({ active, onClick, children, kind = 'default' }) => (
  <button
    type="button"
    className={`bf-pill ${active ? 'is-active' : ''}`}
    data-kind={kind}
    onClick={onClick}
  >
    {children}
  </button>
);

// --- Section header with serif title
const SectionHead = ({ eyebrow, title, action }) => (
  <header className="bf-section-head">
    <div>
      {eyebrow && <div className="bf-eyebrow">{eyebrow}</div>}
      <h2 className="bf-section-title">{title}</h2>
    </div>
    {action}
  </header>
);

// --- Empty state
const EmptyState = ({ icon, title, hint }) => (
  <div className="bf-empty">
    {icon && <div className="bf-empty-icon">{icon}</div>}
    <div className="bf-empty-title">{title}</div>
    {hint && <div className="bf-empty-hint">{hint}</div>}
  </div>
);

// --- Butterfly logo — uses the actual logo image (sage-green rounded square
// with line-art butterfly). For color/size flexibility, an inline SVG version
// could be added later, but the image gives the truest brand mark.
const Logo = ({ size = 32, color }) => (
  <img
    src="logo.jpg"
    alt="Butterfly Coffee"
    width={size}
    height={size}
    style={{
      width: size,
      height: size,
      borderRadius: Math.round(size * 0.22),
      display: 'block',
      objectFit: 'cover',
      // when caller passes `color`, tint via filter for inverse/dark variants
      filter: color === '#f7f3ec' ? 'brightness(1.15)' : undefined,
    }}
  />
);

// --- Number input with stepper
const Stepper = ({ value, onChange, min = 0, max = 99 }) => (
  <div className="bf-stepper">
    <button type="button" onClick={() => onChange(Math.max(min, value - 1))} aria-label="decrease">−</button>
    <span className="bf-stepper-val">{value}</span>
    <button type="button" onClick={() => onChange(Math.min(max, value + 1))} aria-label="increase">+</button>
  </div>
);

// --- Sparkline (mini line chart)
const Sparkline = ({ data, w = 120, h = 32, color = '#2d5240' }) => {
  if (!data || data.length === 0) return null;
  const max = Math.max(...data, 1);
  const min = Math.min(...data, 0);
  const range = max - min || 1;
  const step = w / (data.length - 1 || 1);
  const points = data.map((v, i) => `${i * step},${h - ((v - min) / range) * (h - 4) - 2}`).join(' ');
  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} className="bf-spark">
      <polyline points={points} fill="none" stroke={color} strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round" />
    </svg>
  );
};

// --- Days-of-supply bar
const SupplyBar = ({ days, danger = 5, warn = 10 }) => {
  const status = days <= danger ? 'danger' : days <= warn ? 'warn' : 'ok';
  const pct = Math.min(100, (days / 30) * 100);
  return (
    <div className="bf-supply" data-status={status}>
      <div className="bf-supply-bar"><div className="bf-supply-fill" style={{ width: `${pct}%` }} /></div>
      <div className="bf-supply-label">
        {days < 1 ? 'หมดวันนี้' : `${days.toFixed(0)} วัน`}
      </div>
    </div>
  );
};

Object.assign(window, {
  baht, bahtDecimal, TONE_BG, TempBadge, Card, Stat, Pill,
  SectionHead, EmptyState, Logo, Stepper, Sparkline, SupplyBar
});
