/* O Tal Picolé — shared components */

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

/* ============ LOGO ============ */
function Logo({ size = 30, mark = false }) {
  // Popsicle mark in brand red — simple, geometric, recognizable
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
      <rect x="9.5" y="22.5" width="3" height="6" rx="1" fill="#B3270A" transform="rotate(-12 11 25.5)" />
      <path d="M11.5 4 C 16 4 19 6.5 19 11.5 L 19 19 C 19 21.5 17 23 14 23 C 11 23 9 21.5 9 19 L 9 11.5 C 9 6.5 7 4 11.5 4 Z"
            fill="#D4310B" />
      <path d="M11.5 4 C 14.5 4 17 6 18 9 L 18 12 C 16 11 14 10.5 11.5 10.5 C 9 10.5 7 11 6 12 L 6 9 C 7 6 9 4 11.5 4 Z"
            fill="#E04A1F" opacity=".7" />
      <circle cx="11.5" cy="12" r="1" fill="#FFF7F4" opacity=".6" />
      <circle cx="15.5" cy="15" r=".8" fill="#FFF7F4" opacity=".5" />
      <circle cx="12" cy="16.5" r=".7" fill="#FFF7F4" opacity=".5" />
      {/* Second popsicle behind for depth */}
      <path d="M22 7 C 25 7 26.5 9 26.5 12 L 26.5 17 C 26.5 19 25 20 23 20 C 21 20 19.5 19 19.5 17 L 19.5 12 C 19.5 9 21 7 22 7 Z"
            fill="#1A1A1A" opacity=".88" />
      <rect x="21.5" y="19.5" width="2" height="5" rx=".7" fill="#1A1A1A" opacity=".88" transform="rotate(8 22.5 22)" />
    </svg>
  );
}

/* ============ ICON SET (line, 18px) ============ */
const Icons = {};
const _icon = (paths, vb = "0 0 20 20") => function Icon({ size = 18, color = "currentColor", strokeWidth = 1.6, className = "ic" }) {
  return (
    <svg width={size} height={size} viewBox={vb} fill="none" stroke={color} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" className={className}>
      {paths}
    </svg>
  );
};
Icons.Dashboard = _icon(<><rect x="3" y="3" width="6.5" height="8" rx="1.5"/><rect x="3" y="13" width="6.5" height="4" rx="1.5"/><rect x="11" y="3" width="6" height="4" rx="1.5"/><rect x="11" y="9" width="6" height="8" rx="1.5"/></>);
Icons.Factory = _icon(<><path d="M3 17V9l5 3V9l5 3V5l4 3v9z"/><path d="M3 17h14"/></>);
Icons.Store = _icon(<><path d="M3 8l1-4h12l1 4"/><path d="M4 8v9h12V8"/><path d="M8 17v-4h4v4"/></>);
Icons.Sun = _icon(<><circle cx="10" cy="10" r="3.5"/><path d="M10 2v2M10 16v2M2 10h2M16 10h2M4.2 4.2l1.4 1.4M14.4 14.4l1.4 1.4M4.2 15.8l1.4-1.4M14.4 5.6l1.4-1.4"/></>);
Icons.Users = _icon(<><circle cx="7" cy="7" r="3"/><circle cx="14" cy="8" r="2.4"/><path d="M2 17c0-2.8 2.2-5 5-5s5 2.2 5 5"/><path d="M12 17c0-1.7 1-3.2 2.5-4"/></>);
Icons.Box = _icon(<><path d="M3 7l7-4 7 4-7 4z"/><path d="M3 7v7l7 4 7-4V7"/><path d="M10 11v7"/></>);
Icons.Wallet = _icon(<><rect x="2.5" y="5" width="15" height="11" rx="2"/><path d="M2.5 8h15"/><circle cx="14" cy="12" r="1"/></>);
Icons.Chart = _icon(<><path d="M3 17V3"/><path d="M3 17h14"/><rect x="6" y="11" width="2.4" height="5" rx=".4"/><rect x="10" y="7" width="2.4" height="9" rx=".4"/><rect x="14" y="9" width="2.4" height="7" rx=".4"/></>);
Icons.Settings = _icon(<><circle cx="10" cy="10" r="2.5"/><path d="M10 1.5v2M10 16.5v2M1.5 10h2M16.5 10h2M3.7 3.7l1.4 1.4M14.9 14.9l1.4 1.4M3.7 16.3l1.4-1.4M14.9 5.1l1.4-1.4"/></>);
Icons.Search = _icon(<><circle cx="9" cy="9" r="5.5"/><path d="M13 13l4 4"/></>);
Icons.Bell = _icon(<><path d="M5 8a5 5 0 1110 0c0 4 2 5 2 5H3s2-1 2-5z"/><path d="M8 16a2 2 0 004 0"/></>);
Icons.Plus = _icon(<><path d="M10 4v12M4 10h12"/></>);
Icons.Minus = _icon(<><path d="M4 10h12"/></>);
Icons.Check = _icon(<><path d="M4 10l4 4 8-8"/></>);
Icons.X = _icon(<><path d="M5 5l10 10M15 5L5 15"/></>);
Icons.ArrowUp = _icon(<><path d="M10 16V4M5 9l5-5 5 5"/></>);
Icons.ArrowDown = _icon(<><path d="M10 4v12M5 11l5 5 5-5"/></>);
Icons.ArrowRight = _icon(<><path d="M4 10h12M11 5l5 5-5 5"/></>);
Icons.ChevDown = _icon(<><path d="M5 8l5 5 5-5"/></>);
Icons.Filter = _icon(<><path d="M3 5h14M5 10h10M8 15h4"/></>);
Icons.Calendar = _icon(<><rect x="3" y="4" width="14" height="13" rx="2"/><path d="M3 8h14M7 2v4M13 2v4"/></>);
Icons.Receipt = _icon(<><path d="M5 2v16l2-1 1.5 1L10 17l1.5 1L13 17l2 1V2z"/><path d="M8 6h4M8 9h4M8 12h2"/></>);
Icons.Beach = _icon(<><circle cx="14" cy="5" r="2"/><path d="M14 7v10"/><path d="M14 7c-3 0-5 2-5 5h10c0-3-2-5-5-5z"/><path d="M2 17h16"/></>);
Icons.Truck = _icon(<><rect x="2" y="6" width="10" height="8" rx="1"/><path d="M12 8h3l2.5 3V14H12z"/><circle cx="6" cy="16" r="1.6"/><circle cx="14.5" cy="16" r="1.6"/></>);
Icons.Edit = _icon(<><path d="M4 14l2 4 4-2L17 8l-3-3-7 7z"/><path d="M11 4l3 3"/></>);
Icons.Trash = _icon(<><path d="M4 6h12M7 6V4h6v2M6 6l1 11h6l1-11"/></>);
Icons.More = _icon(<><circle cx="5" cy="10" r="1.2"/><circle cx="10" cy="10" r="1.2"/><circle cx="15" cy="10" r="1.2"/></>);
Icons.Eye = _icon(<><path d="M1.5 10c2-4 5-6 8.5-6s6.5 2 8.5 6c-2 4-5 6-8.5 6S3.5 14 1.5 10z"/><circle cx="10" cy="10" r="2.5"/></>);
Icons.Print = _icon(<><path d="M5 8V3h10v5"/><rect x="2.5" y="8" width="15" height="7" rx="1"/><path d="M5 13h10v4H5z"/></>);
Icons.Download = _icon(<><path d="M10 3v10M5 9l5 5 5-5"/><path d="M3 17h14"/></>);
Icons.Send = _icon(<><path d="M17 3L9 11"/><path d="M17 3l-5 14-3-6-6-3z"/></>);
Icons.AlertTriangle = _icon(<><path d="M10 3l8 14H2z"/><path d="M10 8v4M10 14.5v.5"/></>);
Icons.Snowflake = _icon(<><path d="M10 2v16M2 10h16M3.5 3.5l13 13M16.5 3.5l-13 13"/></>);
Icons.History = _icon(<><path d="M3 10a7 7 0 107-7 7 7 0 00-5 2L3 7"/><path d="M3 3v4h4"/><path d="M10 6v4l3 2"/></>);
Icons.PieChart = _icon(<><path d="M10 3v7h7a7 7 0 11-7-7z"/><path d="M14 3a5 5 0 014 4h-4z"/></>);
Icons.MapPin = _icon(<><path d="M10 18s-6-6-6-11a6 6 0 1112 0c0 5-6 11-6 11z"/><circle cx="10" cy="7" r="2"/></>);
Icons.Coffee = _icon(<><path d="M3 8h11v5a4 4 0 01-4 4H7a4 4 0 01-4-4z"/><path d="M14 9h2a2 2 0 010 4h-2"/><path d="M6 3v2M9 3v2M12 3v2"/></>);
Icons.Star = _icon(<><path d="M10 2l2.4 5 5.6.8-4 4 1 5.6L10 14.8 5 17.4l1-5.6-4-4 5.6-.8z"/></>);
Icons.User = _icon(<><circle cx="10" cy="7" r="3.5"/><path d="M3 17c0-3.5 3-6 7-6s7 2.5 7 6"/></>);
Icons.QrCode = _icon(<><rect x="3" y="3" width="5" height="5"/><rect x="12" y="3" width="5" height="5"/><rect x="3" y="12" width="5" height="5"/><path d="M12 12h2v2M16 12v3M12 16h3M16 16h1"/></>);

/* ============ Helper components ============ */

function Card({ title, subtitle, action, children, flush, className = "", style }) {
  return (
    <div className={"card " + className} style={style}>
      {(title || action) && (
        <div className="card__head">
          <div>
            {title && <h3>{title}</h3>}
            {subtitle && <p>{subtitle}</p>}
          </div>
          {action && <div>{action}</div>}
        </div>
      )}
      <div className={"card__body" + (flush ? " card__body--flush" : "")}>{children}</div>
    </div>
  );
}

function KPI({ label, value, trend, trendDir, sub, icon, medal, tone, sparkline }) {
  const cls = "kpi" + (tone ? " kpi--" + tone : "");
  return (
    <div className={cls}>
      <div className="kpi__top">
        <div className="kpi__label">
          {icon}
          {label}
        </div>
        {medal && <div className="kpi__medal">{medal}</div>}
      </div>
      <div className="kpi__value">{value}</div>
      <div style={{ display:"flex", alignItems:"center", gap:8 }}>
        {trend && (
          <span className={"kpi__trend " + (trendDir || "")}>
            {trendDir === "up" && <Icons.ArrowUp size={11} strokeWidth={2.2} />}
            {trendDir === "down" && <Icons.ArrowDown size={11} strokeWidth={2.2} />}
            {trend}
          </span>
        )}
        {sub && <span className="kpi__sub">{sub}</span>}
      </div>
      {sparkline}
    </div>
  );
}

function Chip({ children, tone, dot }) {
  const cls = "chip" + (tone ? " chip--" + tone : "");
  return <span className={cls}>{dot && <span className="dot" />}{children}</span>;
}

function FlavorTag({ productId }) {
  const p = PRODUCTS.find(x => x.id === productId);
  if (!p) return null;
  return (
    <span className="tag-flavor">
      <span className="sw" style={{ background: p.color }} />
      {p.flavor}
    </span>
  );
}

function Button({ children, variant = "secondary", size, icon, onClick, type = "button", disabled, style }) {
  const cls = "btn btn--" + variant + (size ? " btn--" + size : "");
  return (
    <button type={type} className={cls} onClick={onClick} disabled={disabled} style={style}>
      {icon}
      {children}
    </button>
  );
}

function Field({ label, required, hint, error, children, style }) {
  return (
    <div className="field" style={style}>
      {label && <label>{label} {required && <span className="req">*</span>}</label>}
      {children}
      {hint && !error && <span className="hint">{hint}</span>}
      {error && <span className="err">{error}</span>}
    </div>
  );
}

function Segmented({ options, value, onChange }) {
  return (
    <div className="seg">
      {options.map(opt => (
        <button key={opt.value} className={"seg__btn" + (value === opt.value ? " is-active" : "")} onClick={() => onChange(opt.value)}>
          {opt.label}
        </button>
      ))}
    </div>
  );
}

function Tabs({ items, value, onChange }) {
  return (
    <div className="tabs">
      {items.map(it => (
        <button key={it.value} className={"tabs__btn" + (value === it.value ? " is-active" : "")} onClick={() => onChange(it.value)}>
          {it.label}
        </button>
      ))}
    </div>
  );
}

function Modal({ title, subtitle, size, onClose, children, footer }) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose && onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);
  return (
    <div className="modal-backdrop" onClick={(e) => { if (e.target === e.currentTarget) onClose && onClose(); }}>
      <div className={"modal " + (size === "lg" ? "modal--lg" : "")} role="dialog">
        <div className="modal__head">
          <div>
            <h2>{title}</h2>
            {subtitle && <p>{subtitle}</p>}
          </div>
          <button className="modal__close" onClick={onClose}><Icons.X /></button>
        </div>
        <div className="modal__body">{children}</div>
        {footer && <div className="modal__foot">{footer}</div>}
      </div>
    </div>
  );
}

function Toast({ message, onDone, kind = "success" }) {
  useEffect(() => {
    if (!message) return;
    const t = setTimeout(() => onDone && onDone(), 2400);
    return () => clearTimeout(t);
  }, [message, onDone]);
  if (!message) return null;
  return (
    <div className="toast">
      <span className="ic">{kind === "success" ? <Icons.Check size={16} /> : <Icons.AlertTriangle size={16} />}</span>
      {message}
    </div>
  );
}

function Sparkline({ data, color = "#D4310B", height = 38 }) {
  if (!data || !data.length) return null;
  const w = 120, h = height;
  const min = Math.min(...data), max = Math.max(...data);
  const range = max - min || 1;
  const step = w / (data.length - 1 || 1);
  const pts = data.map((v, i) => `${i*step},${h - ((v - min) / range) * (h - 6) - 3}`).join(" ");
  const area = `M0,${h} L${pts.split(' ').join(' L')} L${w},${h} Z`;
  return (
    <svg className="sparkline" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
      <path d={area} fill={color} opacity=".10" />
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function BarChart({ data, max, color = "var(--brand-600)", alt = "var(--ink-200)", showLabels = true, height = 180 }) {
  const m = max || Math.max(...data.map(d => d.value));
  return (
    <div className="bar-chart" style={{ height }}>
      {data.map((d, i) => {
        const pct = (d.value / m) * 100;
        return (
          <div key={i} className="bar-chart__col">
            <div style={{ width:"100%", display:"flex", alignItems:"flex-end", height: "100%" }}>
              <div className="bar-chart__bar" style={{ height: pct + "%", background: d.alt ? alt : color }} />
            </div>
            {showLabels && <div className="bar-chart__lbl">{d.label}</div>}
          </div>
        );
      })}
    </div>
  );
}

function ProgressBar({ value, max, tone }) {
  const pct = Math.min(100, Math.max(0, (value / max) * 100));
  const cls = "bar" + (tone ? " bar--" + tone : "");
  return <div className={cls}><span style={{ width: pct + "%" }} /></div>;
}

/* Numeric stepper */
function Stepper({ value, onChange, min = 0, max = 9999, step = 1 }) {
  return (
    <div style={{ display:"inline-flex", alignItems:"center", border:"1px solid var(--line-strong)", borderRadius:8, overflow:"hidden", background:"white" }}>
      <button onClick={() => onChange(Math.max(min, value - step))} style={{ width:30, height:32, border:"none", background:"transparent", color:"var(--ink-700)" }}>−</button>
      <input className="numeric" value={value} onChange={(e) => {
        const v = parseInt(e.target.value || "0", 10);
        if (!isNaN(v)) onChange(Math.max(min, Math.min(max, v)));
      }} style={{ width:48, textAlign:"center", border:"none", borderLeft:"1px solid var(--line)", borderRight:"1px solid var(--line)", padding:"6px 4px", outline:"none", background:"white", fontWeight:600 }} />
      <button onClick={() => onChange(Math.min(max, value + step))} style={{ width:30, height:32, border:"none", background:"transparent", color:"var(--ink-700)" }}>+</button>
    </div>
  );
}

function Steps({ items, current }) {
  return (
    <div className="steps">
      {items.map((it, i) => (
        <React.Fragment key={i}>
          <div className={"steps__item " + (i < current ? "is-done " : "") + (i === current ? "is-current" : "")}>
            <div className="steps__num">{i < current ? <Icons.Check size={14} strokeWidth={2.4} /> : i + 1}</div>
            <div className="steps__lbl">{it}</div>
          </div>
          {i < items.length - 1 && <div className="steps__line" />}
        </React.Fragment>
      ))}
    </div>
  );
}

/* Donut chart */
function Donut({ segments, size = 140, thickness = 18, total }) {
  const r = (size - thickness) / 2;
  const c = 2 * Math.PI * r;
  const sum = total || segments.reduce((s, x) => s + x.value, 0);
  let offset = 0;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--ink-100)" strokeWidth={thickness} />
      {segments.map((s, i) => {
        const len = (s.value / sum) * c;
        const dasharray = `${len} ${c - len}`;
        const dashoffset = -offset;
        offset += len;
        return (
          <circle key={i} cx={size/2} cy={size/2} r={r} fill="none"
                  stroke={s.color} strokeWidth={thickness}
                  strokeDasharray={dasharray} strokeDashoffset={dashoffset}
                  transform={`rotate(-90 ${size/2} ${size/2})`} strokeLinecap="butt" />
        );
      })}
    </svg>
  );
}

/* Section header inside a page */
function SectionHead({ title, subtitle, action }) {
  return (
    <div style={{ display:"flex", alignItems:"flex-end", justifyContent:"space-between", marginBottom: 12, gap:12 }}>
      <div>
        <h2 style={{ margin:0, fontSize:16, fontWeight:600, color:"var(--ink-900)", letterSpacing:"-.005em" }}>{title}</h2>
        {subtitle && <p style={{ margin: "2px 0 0", color:"var(--ink-500)", fontSize:12.5 }}>{subtitle}</p>}
      </div>
      {action}
    </div>
  );
}

Object.assign(window, {
  Logo, Icons, Card, KPI, Chip, FlavorTag, Button, Field, Segmented, Tabs,
  Modal, Toast, Sparkline, BarChart, ProgressBar, Stepper, Steps, Donut, SectionHead,
});
