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

/* ── Utilities ─────────────────────────────────────── */
function nameToColor(name) {
  let h = 0;
  for (let i = 0; i < name.length; i++) h = name.charCodeAt(i) + ((h << 5) - h);
  return `oklch(0.72 0.12 ${Math.abs(h % 360)})`;
}
function nameToInitials(name) {
  if (name === "Guest") return "G";
  if (name === "LounaCOFFEE") return "LC";
  return name.slice(0, 2).toUpperCase();
}
function textOnColor(hex) {
  const r = parseInt(hex.slice(1,3),16), g = parseInt(hex.slice(3,5),16), b = parseInt(hex.slice(5,7),16);
  return (0.299*r + 0.587*g + 0.114*b) / 255 > 0.55 ? '#333' : '#fff';
}

/* ── Header ────────────────────────────────────────── */
function Header({ screen, onBack, onCarWash, accentColor }) {
  const isCW = screen === 'carwash' || screen === 'carwash-person';
  const now = new Date();
  const mo = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
  const period = `${mo[now.getMonth()]} ${now.getFullYear()}`;

  return (
    <header className="hdr">
      <div className="hdr-left">
        {screen !== "shop" && (
          <button className="hdr-back" onClick={onBack} aria-label="Back">
            <svg width="22" height="22" viewBox="0 0 22 22" fill="none"><path d="M14 5L7 11L14 17" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
        )}
        <div className="hdr-logo">
          <img src="uploads/Logo_Transparent.png" className="hdr-logo-img" alt="Yellow" />
          <span className="hdr-logo-sep"></span>
          <span className="hdr-logo-text">Snack Overflow</span>
        </div>
      </div>
      <div className="hdr-right">
        <div className="hdr-period">Billing&nbsp;&nbsp;<strong>{period}</strong></div>
        <button className="hdr-admin" title="Car Wash" onClick={onCarWash}
          style={{
            border: 'none',
            background: isCW ? (accentColor + '20') : 'transparent',
            color: isCW ? 'var(--text)' : 'var(--text2)',
          }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22a7 7 0 007-7c0-4-3.5-8-7-12-3.5 4-7 8-7 12a7 7 0 007 7z"/></svg>
        </button>
        <a href="Kitchen.html" className="hdr-admin" title="Kitchen Display" style={{marginRight: 2}}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18"/><path d="M9 21V9"/></svg>
        </a>
        <a href="Car Wash Display.html" className="hdr-admin" title="Washer Display" style={{marginRight: 2}}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 12h18"/><path d="M12 3v18"/></svg>
        </a>
        <a href="/admin" className="hdr-admin" title="Admin Panel">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12.22 2h-.44a2 2 0 00-2 2v.18a2 2 0 01-1 1.73l-.43.25a2 2 0 01-2 0l-.15-.08a2 2 0 00-2.73.73l-.22.38a2 2 0 00.73 2.73l.15.1a2 2 0 011 1.72v.51a2 2 0 01-1 1.74l-.15.09a2 2 0 00-.73 2.73l.22.38a2 2 0 002.73.73l.15-.08a2 2 0 012 0l.43.25a2 2 0 011 1.73V20a2 2 0 002 2h.44a2 2 0 002-2v-.18a2 2 0 011-1.73l.43-.25a2 2 0 012 0l.15.08a2 2 0 002.73-.73l.22-.39a2 2 0 00-.73-2.73l-.15-.08a2 2 0 01-1-1.74v-.5a2 2 0 011-1.74l.15-.09a2 2 0 00.73-2.73l-.22-.38a2 2 0 00-2.73-.73l-.15.08a2 2 0 01-2 0l-.43-.25a2 2 0 01-1-1.73V4a2 2 0 00-2-2z"/><circle cx="12" cy="12" r="3"/></svg>
        </a>
      </div>
    </header>
  );
}

/* ── Item Card ─────────────────────────────────────── */
function ItemCard({ item, qty, onAdd, onRemove, onConfigure, configQty = 0, accent }) {
  const cc = CATEGORY_COLORS[item.category] || { bg: "#f3f4f6", fg: "#6b7280" };
  const isCfg = item.configurable;
  const totalQty = isCfg ? configQty : qty;
  const inCart = totalQty > 0;
  const [pulse, setPulse] = useState(false);

  const handleClick = () => {
    if (isCfg) { onConfigure && onConfigure(item); return; }
    onAdd(item.id); setPulse(true); setTimeout(() => setPulse(false), 200);
  };

  const displayPrice = isCfg
    ? item.steps.reduce((s, step) => s + (step.required && step.options.length ? Math.min(...step.options.map(o => o.price)) : 0), 0)
    : item.price;

  return (
    <div
      className={`card ${inCart ? "card--active" : ""} ${pulse ? "card--pulse" : ""}`}
      style={inCart ? { borderColor: accent, boxShadow: `0 0 0 1px ${accent}30` } : undefined}
    >
      {inCart && <span className="card-badge" style={{background: accent, color: textOnColor(accent)}}>{totalQty}</span>}
      {isCfg && <span className="card-tag" style={{background: cc.bg, color: cc.fg}}>Customise</span>}

      <div className="card-img" style={{background: item.image_url ? 'transparent' : cc.bg}} onClick={handleClick}>
        {item.image_url
          ? <img src={item.image_url} alt={item.name} style={{width:'100%',height:'100%',objectFit:'cover'}} />
          : <React.Fragment><span className="card-letter" style={{color: cc.fg}}>{item.name[0]}</span><span className="card-ph">product photo</span></React.Fragment>}
      </div>

      <div className="card-body" onClick={handleClick}>
        <div className="card-name">{item.name}</div>
        {item.subtitle && <div className="card-sub">{item.subtitle}</div>}
        <div className="card-price">
          {isCfg && <span className="card-from">from </span>}
          R{displayPrice.toFixed(2)}
        </div>
      </div>

      {inCart && !isCfg && (
        <div className="card-qty" onClick={e => e.stopPropagation()}>
          <button className="qty-btn qty-minus" onClick={() => onRemove(item.id)}>−</button>
          <span className="qty-val">{qty}</span>
          <button className="qty-btn qty-plus" style={{background: accent, color: textOnColor(accent)}} onClick={() => onAdd(item.id)}>+</button>
        </div>
      )}
    </div>
  );
}

/* ── Shop Screen ───────────────────────────────────── */
function ShopScreen({ cart, configCart, onAdd, onRemove, onConfigure, accent }) {
  const [cat, setCat] = useState("all");
  const items = cat === "all" ? SNACK_ITEMS : SNACK_ITEMS.filter(i => i.category === cat);

  const cfgQtyMap = useMemo(() => {
    const m = {};
    (configCart || []).forEach(ci => { m[ci.itemId] = (m[ci.itemId] || 0) + ci.qty; });
    return m;
  }, [configCart]);

  return (
    <div className="shop">
      <div className="tabs">
        {CATEGORIES.map(c => (
          <button
            key={c.id}
            className={`tab ${cat === c.id ? "tab--on" : ""}`}
            style={cat === c.id ? { background: accent, color: textOnColor(accent), borderColor: accent } : undefined}
            onClick={() => setCat(c.id)}
          >{c.label}</button>
        ))}
      </div>
      <div className="grid">
        {items.map(i => (
          <ItemCard key={i.id} item={i} qty={cart[i.id] || 0}
            configQty={cfgQtyMap[i.id] || 0}
            onAdd={onAdd} onRemove={onRemove} onConfigure={onConfigure} accent={accent} />
        ))}
      </div>
    </div>
  );
}

/* ── Cart Bar ──────────────────────────────────────── */
function CartBar({ cart, configCart, onCheckout, onClear, accent }) {
  const [open, setOpen] = useState(false);
  const rows = Object.entries(cart).filter(([,q]) => q > 0).map(([id, q]) => {
    const it = SNACK_ITEMS.find(x => x.id === +id);
    return { ...it, qty: q, line: it.price * q };
  });
  const cfgRows = (configCart || []).map(ci => ({
    id: ci.uid, name: ci.name,
    desc: ci.summaryLines.map(l => l.name).join(", "),
    summaryLines: ci.summaryLines,
    configurable: true,
    qty: ci.qty, price: ci.unitPrice,
    line: ci.unitPrice * ci.qty,
  }));
  const allRows = [...rows, ...cfgRows];
  const total = allRows.reduce((s, r) => s + r.line, 0);
  const count = allRows.reduce((s, r) => s + r.qty, 0);
  if (count === 0) return null;

  return (
    <div className={`cbar ${open ? "cbar--open" : ""}`}>
      {open && (
        <div className="cbar-detail">
          {allRows.map(r => (
            <div key={r.id} className="cbar-row">
              <div><span>{r.qty}× {r.name}</span>{r.desc && <div style={{fontSize:11,opacity:.6,marginTop:1}}>{r.desc}</div>}</div>
              <span>R{r.line.toFixed(2)}</span>
            </div>
          ))}
        </div>
      )}
      <div className="cbar-main">
        <button className="cbar-toggle" onClick={() => setOpen(o => !o)}>
          <svg width="20" height="20" viewBox="0 0 20 20" fill="none" style={{marginRight:8}}>
            <path d="M6 6h12l-2 8H8L6 6z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/>
            <path d="M6 6L5 2H2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
            <circle cx="9" cy="17" r="1.2" fill="currentColor"/><circle cx="15" cy="17" r="1.2" fill="currentColor"/>
          </svg>
          <span className="cbar-count">{count} item{count !== 1 ? "s" : ""}</span>
          <span className="cbar-total">R{total.toFixed(2)}</span>
        </button>
        <div className="cbar-actions">
          <button className="cbar-clear" onClick={onClear}>Clear</button>
          <button className="cbar-go" style={{background: accent, color: textOnColor(accent)}} onClick={() => onCheckout(allRows, total)}>
            Charge to
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" style={{marginLeft:6}}>
              <path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>
      </div>
    </div>
  );
}

/* ── Person Picker ─────────────────────────────────── */
function PersonScreen({ items, total, onSelect, accent, title, subtitle }) {
  const [q, setQ] = useState("");
  const ref = useRef(null);
  useEffect(() => { ref.current && ref.current.focus(); }, []);

  const list = q ? EMPLOYEES.filter(n => n.toLowerCase().includes(q.toLowerCase())) : EMPLOYEES;

  return (
    <div className="who">
      <div className="who-head">
        <h2 className="who-title">{title || "Who's buying?"}</h2>
        <p className="who-summary">{subtitle || `${items.length} item${items.length !== 1 ? 's' : ''} · R${total.toFixed(2)}`}</p>
      </div>
      <div className="who-search">
        <svg className="who-search-icon" width="18" height="18" viewBox="0 0 18 18" fill="none">
          <circle cx="8" cy="8" r="5.5" stroke="currentColor" strokeWidth="1.5"/>
          <path d="M12 12l4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
        </svg>
        <input ref={ref} className="who-input" placeholder="Search employee…" value={q} onChange={e => setQ(e.target.value)} />
        {q && <button className="who-clear" onClick={() => setQ("")}>×</button>}
      </div>
      <div className="who-grid">
        {list.map(name => (
          <button key={name} className="who-btn" onClick={() => onSelect(name)}>
            <span className="who-avatar" style={{background: nameToColor(name)}}>{nameToInitials(name)}</span>
            <span className="who-name">{name}</span>
          </button>
        ))}
        {list.length === 0 && <p className="who-empty">No employees found</p>}
      </div>
    </div>
  );
}

/* ── Confirm Dialog ────────────────────────────────── */
function ConfirmDialog({ person, items, total, tab, onConfirm, onCancel, accent }) {
  return (
    <div className="overlay" onClick={onCancel}>
      <div className="confirm" onClick={e => e.stopPropagation()}>
        <div className="confirm-who">
          <span className="confirm-av" style={{background: nameToColor(person)}}>{nameToInitials(person)}</span>
          <div>
            <div className="confirm-name">{person}</div>
            <div className="confirm-curtab">Current tab: R{tab.toFixed(2)}</div>
          </div>
        </div>
        <div className="confirm-items">
          {items.map(r => (
            <div key={r.id} className="confirm-row">
              <div><span>{r.qty}× {r.name}</span>{r.desc && <div style={{fontSize:11,color:'var(--text2)',marginTop:1}}>{r.desc}</div>}</div>
              <span>R{r.line.toFixed(2)}</span>
            </div>
          ))}
        </div>
        <div className="confirm-total-row">
          <span>Total</span><span className="confirm-total">R{total.toFixed(2)}</span>
        </div>
        <div className="confirm-newtab">New tab: <strong>R{(tab + total).toFixed(2)}</strong></div>
        <div className="confirm-acts">
          <button className="btn-cancel" onClick={onCancel}>Cancel</button>
          <button className="btn-confirm" style={{background: accent, color: textOnColor(accent)}} onClick={onConfirm}>Confirm Charge</button>
        </div>
      </div>
    </div>
  );
}

/* ── Success: Modal ────────────────────────────────── */
function SuccessModal({ person, items, total, newTab, onDismiss, accent }) {
  const [pct, setPct] = useState(100);
  const timer = useRef(null);
  useEffect(() => {
    const dur = 5000, iv = 50, step = 100 / dur * iv;
    timer.current = setInterval(() => setPct(p => { if (p <= 0) { clearInterval(timer.current); onDismiss(); return 0; } return p - step; }), iv);
    return () => clearInterval(timer.current);
  }, [onDismiss]);

  return (
    <div className="overlay overlay--success" onClick={onDismiss}>
      <div className="smodal" onClick={e => e.stopPropagation()}>
        <div className="smodal-check">
          <svg width="36" height="36" viewBox="0 0 36 36" fill="none"><path d="M9 18l6 6 12-12" stroke="#16a34a" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" className="check-path"/></svg>
        </div>
        <h3 className="smodal-title">Sale Complete</h3>
        <div className="smodal-who">
          <span className="smodal-av" style={{background: nameToColor(person)}}>{nameToInitials(person)}</span>
          <div>
            <div className="smodal-charged">Charged to <strong>{person}</strong></div>
            <div className="smodal-amount">R{total.toFixed(2)}</div>
          </div>
        </div>
        <div className="smodal-items">
          {items.map(r => <div key={r.id} className="smodal-row"><span>{r.qty}× {r.name}</span><span>R{r.line.toFixed(2)}</span></div>)}
        </div>
        <div className="smodal-tab">Monthly tab: <strong>R{newTab.toFixed(2)}</strong></div>
        <div className="smodal-bar"><div className="smodal-fill" style={{width: pct + "%", background: accent}}></div></div>
        <button className="smodal-done" onClick={onDismiss}>Done</button>
      </div>
    </div>
  );
}

/* ── Success: Toast ────────────────────────────────── */
function SuccessToast({ person, total, newTab, onDismiss, accent }) {
  const [pct, setPct] = useState(100);
  useEffect(() => {
    const dur = 4000, iv = 50, step = 100 / dur * iv;
    const t = setInterval(() => setPct(p => { if (p <= 0) { clearInterval(t); onDismiss(); return 0; } return p - step; }), iv);
    return () => clearInterval(t);
  }, [onDismiss]);

  return (
    <div className="toast">
      <div className="toast-bar" style={{width: pct + "%", background: accent}}></div>
      <div className="toast-body">
        <span className="toast-check">
          <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><path d="M5 10l4 4 6-8" stroke="#16a34a" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </span>
        <div className="toast-text">
          <div className="toast-main">R{total.toFixed(2)} charged to <strong>{person}</strong></div>
          <div className="toast-sub">Monthly tab: R{newTab.toFixed(2)}</div>
        </div>
        <button className="toast-x" onClick={onDismiss}>×</button>
      </div>
    </div>
  );
}

/* ── Success: Full-screen ──────────────────────────── */
function SuccessFullScreen({ person, total, newTab, onDismiss, accent }) {
  const [phase, setPhase] = useState("enter");
  useEffect(() => {
    const t1 = setTimeout(() => setPhase("show"), 80);
    const t2 = setTimeout(() => setPhase("exit"), 3000);
    const t3 = setTimeout(onDismiss, 3500);
    return () => { clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); };
  }, [onDismiss]);

  return (
    <div className={`fscreen fscreen--${phase}`} onClick={onDismiss}>
      <div className="fscreen-ring" style={{borderColor: "#16a34a"}}>
        <svg width="52" height="52" viewBox="0 0 52 52" fill="none"><path d="M14 26l8 8 16-16" stroke="#16a34a" strokeWidth="4" strokeLinecap="round" strokeLinejoin="round" className="check-path"/></svg>
      </div>
      <div className="fscreen-amt">R{total.toFixed(2)}</div>
      <div className="fscreen-who">Charged to <strong>{person}</strong></div>
      <div className="fscreen-tab">Monthly tab: R{newTab.toFixed(2)}</div>
    </div>
  );
}

/* ── Export to window ──────────────────────────────── */
Object.assign(window, {
  Header, ShopScreen, CartBar, PersonScreen, ConfirmDialog,
  SuccessModal, SuccessToast, SuccessFullScreen,
  nameToColor, nameToInitials, textOnColor, ItemCard,
});
