/* Vito's Wings — Kitchen Dashboard (admin view)
   Accessed via ?admin=1 or by clicking the kitchen button in the dev footer. */

const KITCHEN_STAGES = [
  { id: "new",       en: "New",        es: "Nuevos",        color: "#E63426", icon: "🔔" },
  { id: "prep",      en: "Preparing",  es: "Preparando",    color: "#D97706", icon: "🍳" },
  { id: "ready",     en: "Ready",      es: "Listas",        color: "#15803D", icon: "✓" },
  { id: "done",      en: "Picked up",  es: "Entregadas",    color: "#525252", icon: "📦" },
];

// Seed orders so the dashboard looks alive on first load
const SEED_ORDERS = [
  {
    id: "VW-1042", customer: "Andrea M.", phone: "+504 9988-1122",
    placed: Date.now() - 1000 * 60 * 2, pickupAt: "ASAP",
    paid: true, payMethod: "online", total: 540,
    stage: "new",
    items: [
      { name: "Vito's Para Dos", qty: 1, price: 540, sauces: ["Lemon Pepper", "Hot Honey"], notes: "Salsas aparte por favor" },
    ],
  },
  {
    id: "VW-1041", customer: "Carlos R.", phone: "+504 3344-5566",
    placed: Date.now() - 1000 * 60 * 5, pickupAt: "30 min",
    paid: false, payMethod: "pickup", total: 425,
    stage: "new",
    items: [
      { name: "Wings (9 pcs)", qty: 1, price: 280, sauces: ["Buffalo"], notes: "" },
      { name: "Loaded Fries", qty: 1, price: 145, sauces: [], notes: "" },
    ],
  },
  {
    id: "VW-1040", customer: "Sofia L.", phone: "+504 9211-3344",
    placed: Date.now() - 1000 * 60 * 9, pickupAt: "ASAP",
    paid: true, payMethod: "online", total: 360,
    stage: "prep",
    items: [
      { name: "Vito's Burger", qty: 1, price: 280, sauces: [], notes: "Sin cebolla" },
      { name: "Pepsi Black", qty: 1, price: 45, sauces: [], notes: "" },
      { name: "Honey Mustard (extra)", qty: 1, price: 35, sauces: [], notes: "" },
    ],
  },
  {
    id: "VW-1039", customer: "Diego H.", phone: "+504 8877-2200",
    placed: Date.now() - 1000 * 60 * 14, pickupAt: "ASAP",
    paid: true, payMethod: "online", total: 815,
    stage: "prep",
    items: [
      { name: "Vito's Sampler Box", qty: 1, price: 815, sauces: ["Lemon Pepper", "BBQ", "Hot Honey"], notes: "Cumpleaños de mi novia — pueden agregar un sticker?" },
    ],
  },
  {
    id: "VW-1038", customer: "Mariela G.", phone: "+504 9933-4455",
    placed: Date.now() - 1000 * 60 * 21, pickupAt: "ASAP",
    paid: true, payMethod: "online", total: 285,
    stage: "ready",
    items: [
      { name: "Boneless (9 pcs)", qty: 1, price: 285, sauces: ["Garlic Parmesan"], notes: "" },
    ],
  },
];

function ScreenKitchen({ lang, exit }) {
  const [orders, setOrders] = useState(SEED_ORDERS);
  const [sound, setSound] = useState(true);
  const [waNotify, setWaNotify] = useState(true);
  const [now, setNow] = useState(Date.now());
  const [toast, setToast] = useState(null);
  const [activeStage, setActiveStage] = useState("new"); // mobile: which column is visible
  const lastOrderCount = useRef(orders.filter(o => o.stage === "new").length);

  // tick clock
  useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);

  // Simulated incoming order every ~25s for demo
  useEffect(() => {
    const id = setInterval(() => {
      const seed = randomOrder();
      setOrders(o => [seed, ...o]);
      if (sound) playDing();
      showToast(lang === "es" ? `🔔 Nuevo pedido ${seed.id} · ${seed.customer}` : `🔔 New order ${seed.id} · ${seed.customer}`);
      if (waNotify) {
        showToast(lang === "es" ? `💬 WhatsApp enviado al dueño · ${seed.id}` : `💬 WhatsApp sent to owner · ${seed.id}`, 4500);
      }
    }, 28000);
    return () => clearInterval(id);
  }, [sound, waNotify, lang]);

  function showToast(msg, delay) {
    setToast(msg);
    setTimeout(() => setToast(null), delay || 3500);
  }

  function advance(id) {
    setOrders(o => o.map(ord => {
      if (ord.id !== id) return ord;
      const idx = KITCHEN_STAGES.findIndex(s => s.id === ord.stage);
      const next = KITCHEN_STAGES[Math.min(idx + 1, KITCHEN_STAGES.length - 1)].id;
      if (next === "ready") showToast(lang === "es" ? `💬 WhatsApp a ${ord.customer}: "Tu orden está lista 🐶"` : `💬 WhatsApp to ${ord.customer}: "Your order is ready 🐶"`);
      return { ...ord, stage: next };
    }));
  }

  function regress(id) {
    setOrders(o => o.map(ord => {
      if (ord.id !== id) return ord;
      const idx = KITCHEN_STAGES.findIndex(s => s.id === ord.stage);
      const prev = KITCHEN_STAGES[Math.max(idx - 1, 0)].id;
      return { ...ord, stage: prev };
    }));
  }

  function markPaid(id) {
    setOrders(o => o.map(ord => ord.id === id ? { ...ord, paid: true, payMethod: "pickup-paid" } : ord));
    showToast(lang === "es" ? "✓ Marcado como pagado" : "✓ Marked as paid");
  }

  function playDing() {
    try {
      const ctx = new (window.AudioContext || window.webkitAudioContext)();
      const o = ctx.createOscillator();
      const g = ctx.createGain();
      o.connect(g); g.connect(ctx.destination);
      o.frequency.value = 880;
      g.gain.setValueAtTime(0.15, ctx.currentTime);
      g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.4);
      o.start(); o.stop(ctx.currentTime + 0.4);
    } catch {}
  }

  function randomOrder() {
    const pool = [
      { items: [{ name: "Wings (12 pcs)", qty: 1, price: 335, sauces: ["Hot Lemon Pepper"], notes: "" }], total: 335 },
      { items: [{ name: "Boneless (6 pcs)", qty: 1, price: 205, sauces: ["Sweet Chili"], notes: "" }, { name: "Lemonade", qty: 1, price: 65, sauces: [], notes: "" }], total: 270 },
      { items: [{ name: "Vito's Burger", qty: 2, price: 280, sauces: [], notes: "Una sin tomate" }], total: 560 },
      { items: [{ name: "Truffled Fries", qty: 1, price: 315, sauces: [], notes: "" }, { name: "Mojito", qty: 1, price: 175, sauces: [], notes: "" }], total: 490 },
    ];
    const names = ["Roberto P.", "Camila V.", "Esteban M.", "Lucía F.", "Pablo C.", "Renata D."];
    const pick = pool[Math.floor(Math.random() * pool.length)];
    const idNum = 1043 + Math.floor(Math.random() * 999);
    return {
      id: "VW-" + idNum,
      customer: names[Math.floor(Math.random() * names.length)],
      phone: "+504 " + Math.floor(1000 + Math.random() * 8999) + "-" + Math.floor(1000 + Math.random() * 8999),
      placed: Date.now(),
      pickupAt: "ASAP",
      paid: Math.random() > 0.3,
      payMethod: Math.random() > 0.3 ? "online" : "pickup",
      total: pick.total,
      stage: "new",
      items: pick.items,
    };
  }

  const groups = KITCHEN_STAGES.map(s => ({
    ...s,
    orders: orders.filter(o => o.stage === s.id),
  }));

  const newCount = groups.find(g => g.id === "new").orders.length;
  const prepCount = groups.find(g => g.id === "prep").orders.length;
  const todayTotal = orders.reduce((s, o) => s + o.total, 0);
  const todayPaid = orders.filter(o => o.paid).reduce((s, o) => s + o.total, 0);

  return (
    <div style={{ minHeight: "100vh", background: "#0A0A0A", color: "#F6F4EF", fontFamily: "'DM Sans', sans-serif" }}>
      {/* Top bar */}
      <header className="vw-kitchen-header" style={{
        position: "sticky", top: 0, zIndex: 30, background: "#0A0A0A",
        borderBottom: "1px solid rgba(246,244,239,0.2)",
        padding: "12px 16px",
        display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12,
        flexWrap: "wrap",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, minWidth: 0 }}>
          <img src="assets/vitos-icon.png" alt="" style={{ height: 28, filter: "invert(1)", flexShrink: 0 }} />
          <div style={{ minWidth: 0 }}>
            <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 18, letterSpacing: "0.08em", lineHeight: 1 }}>KITCHEN · COCINA</div>
            <div style={{ fontSize: 10, letterSpacing: "0.2em", color: "rgba(246,244,239,0.5)", marginTop: 4 }}>
              {new Date(now).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })} · {lang === "es" ? "EN VIVO" : "LIVE"} <span style={{ animation: "vwBlink 1s infinite", color: "#E63426" }}>●</span>
            </div>
          </div>
        </div>

        <div className="vw-kitchen-stats" style={{ display: "flex", gap: 18, alignItems: "center", overflowX: "auto", flexShrink: 1 }}>
          <Stat label={lang === "es" ? "NUEVOS" : "NEW"} value={newCount} color="#E63426" />
          <Stat label={lang === "es" ? "EN PREP" : "PREP"} value={prepCount} color="#D97706" />
          <Stat label={lang === "es" ? "VENTAS" : "TODAY"} value={fmtL(todayTotal)} small />
          <Stat label={lang === "es" ? "PAGADO" : "PAID"} value={fmtL(todayPaid)} small color="#15803D" />
        </div>

        <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
          <Toggle on={sound} onChange={setSound} label="🔔" />
          <Toggle on={waNotify} onChange={setWaNotify} label="💬" />
          <button onClick={exit} style={{
            appearance: "none", border: "1px solid rgba(246,244,239,0.3)", background: "transparent",
            color: "#F6F4EF", padding: "8px 12px", fontFamily: "'Anton', sans-serif",
            fontSize: 11, letterSpacing: "0.16em", cursor: "pointer",
          }}>← {lang === "es" ? "SITIO" : "SITE"}</button>
        </div>
      </header>

      {/* Mobile stage tabs */}
      <div className="vw-kitchen-tabs" style={{
        display: "none",
        position: "sticky", top: 0, zIndex: 25,
        background: "#0A0A0A", borderBottom: "1px solid rgba(246,244,239,0.15)",
        padding: "8px 8px", gap: 6,
        overflowX: "auto",
      }}>
        {groups.map(g => (
          <button key={g.id} onClick={() => setActiveStage(g.id)} style={{
            appearance: "none",
            background: activeStage === g.id ? g.color : "transparent",
            border: "1px solid " + (activeStage === g.id ? g.color : "rgba(246,244,239,0.2)"),
            color: "#F6F4EF",
            padding: "10px 12px", cursor: "pointer", whiteSpace: "nowrap",
            display: "flex", alignItems: "center", gap: 8,
            fontFamily: "'Anton', sans-serif", fontSize: 13, letterSpacing: "0.1em",
            flexShrink: 0,
          }}>
            <span>{g.icon}</span>
            <span>{g[lang].toUpperCase()}</span>
            <span style={{
              background: activeStage === g.id ? "rgba(0,0,0,0.3)" : g.color,
              padding: "2px 7px", fontSize: 12, minWidth: 22, textAlign: "center",
            }}>{g.orders.length}</span>
          </button>
        ))}
      </div>

      {/* Columns */}
      <div style={{
        display: "grid",
        gridTemplateColumns: "repeat(4, 1fr)",
        gap: 1,
        background: "rgba(246,244,239,0.1)",
        minHeight: "calc(100vh - 66px)",
      }} className="vw-kitchen-grid" data-active={activeStage}>
        {groups.map(g => (
          <div key={g.id} data-stage={g.id} className={g.id === activeStage ? "vw-stage-on" : "vw-stage-off"} style={{ background: "#0A0A0A", display: "flex", flexDirection: "column" }}>
            <div className="vw-kitchen-coltitle" style={{
              padding: "16px 18px",
              borderBottom: "2px solid " + g.color,
              display: "flex", justifyContent: "space-between", alignItems: "center",
              position: "sticky", top: 66, background: "#0A0A0A", zIndex: 10,
            }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{ fontSize: 22 }}>{g.icon}</span>
                <span style={{ fontFamily: "'Anton', sans-serif", fontSize: 20, letterSpacing: "0.1em" }}>{g[lang].toUpperCase()}</span>
              </div>
              <span style={{ background: g.color, color: "#F6F4EF", padding: "4px 10px", fontFamily: "'Anton', sans-serif", fontSize: 14, letterSpacing: "0.06em", minWidth: 28, textAlign: "center" }}>{g.orders.length}</span>
            </div>

            <div style={{ flex: 1, padding: 12, display: "flex", flexDirection: "column", gap: 10, overflowY: "auto", maxHeight: "calc(100vh - 140px)" }}>
              {g.orders.length === 0 ? (
                <div style={{ padding: "40px 12px", textAlign: "center", color: "rgba(246,244,239,0.3)", fontSize: 13, letterSpacing: "0.18em" }}>
                  {lang === "es" ? "VACÍO" : "EMPTY"}
                </div>
              ) : g.orders.map(o => (
                <KitchenCard key={o.id} order={o} lang={lang} now={now}
                  onAdvance={() => advance(o.id)}
                  onRegress={() => regress(o.id)}
                  onMarkPaid={() => markPaid(o.id)}
                  isLast={g.id === "done"}
                  isFirst={g.id === "new"}
                />
              ))}
            </div>
          </div>
        ))}
      </div>

      {/* Toast */}
      {toast && (
        <div style={{
          position: "fixed", bottom: 24, right: 24, zIndex: 100,
          background: "#F6F4EF", color: "#0A0A0A",
          padding: "14px 18px", border: "2px solid #0A0A0A",
          boxShadow: "6px 6px 0 #E63426",
          fontSize: 14, fontFamily: "'DM Sans', sans-serif", fontWeight: 600,
          maxWidth: 360, animation: "vwPop 0.25s",
        }}>{toast}</div>
      )}
    </div>
  );
}

// ---- Helper components ----
function Stat({ label, value, color, small }) {
  return (
    <div style={{ textAlign: "center" }}>
      <div style={{ fontSize: 10, letterSpacing: "0.22em", color: "rgba(246,244,239,0.5)", fontWeight: 700 }}>{label}</div>
      <div style={{ fontFamily: "'Anton', sans-serif", fontSize: small ? 22 : 30, color: color || "#F6F4EF", lineHeight: 1, marginTop: 2 }}>{value}</div>
    </div>
  );
}

function Toggle({ on, onChange, label }) {
  return (
    <button onClick={() => onChange(!on)} style={{
      appearance: "none", background: on ? "#15803D" : "transparent",
      border: "1px solid " + (on ? "#15803D" : "rgba(246,244,239,0.3)"),
      color: "#F6F4EF", padding: "8px 12px", cursor: "pointer",
      fontFamily: "'DM Sans', sans-serif", fontSize: 12, fontWeight: 700, letterSpacing: "0.12em",
      display: "flex", alignItems: "center", gap: 4,
    }}>
      <span style={{ width: 8, height: 8, borderRadius: "50%", background: on ? "#F6F4EF" : "rgba(246,244,239,0.3)" }} />
      {label}
    </button>
  );
}

function KitchenCard({ order, lang, now, onAdvance, onRegress, onMarkPaid, isLast, isFirst }) {
  const ageMin = Math.floor((now - order.placed) / 60000);
  const ageColor = ageMin > 15 ? "#E63426" : ageMin > 8 ? "#D97706" : "rgba(246,244,239,0.5)";

  return (
    <div style={{
      background: "#1a1a1a", border: isFirst ? "1px solid #E63426" : "1px solid rgba(246,244,239,0.15)",
      padding: 14, display: "flex", flexDirection: "column", gap: 8,
      animation: isFirst && ageMin < 1 ? "vwNewOrder 0.6s ease" : "none",
    }}>
      {/* Header row */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 16, letterSpacing: "0.06em" }}>{order.id}</div>
        <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 14, color: ageColor }}>
          {ageMin < 1 ? (lang === "es" ? "AHORA" : "NOW") : `${ageMin}m`}
        </div>
      </div>

      {/* Customer */}
      <div style={{ fontSize: 13, fontWeight: 600 }}>
        {order.customer}
        <span style={{ color: "rgba(246,244,239,0.5)", fontWeight: 400, marginLeft: 6 }}>· {order.phone}</span>
      </div>

      {/* Payment badge */}
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
        {order.paid ? (
          <span style={{ background: "#15803D", color: "#F6F4EF", padding: "3px 8px", fontSize: 10, letterSpacing: "0.18em", fontFamily: "'DM Sans', sans-serif", fontWeight: 700 }}>
            ✓ {lang === "es" ? "PAGADO" : "PAID"} · {order.payMethod === "online" ? (lang === "es" ? "TARJETA" : "CARD") : (lang === "es" ? "EFECTIVO" : "CASH")}
          </span>
        ) : (
          <span style={{ background: "#D97706", color: "#F6F4EF", padding: "3px 8px", fontSize: 10, letterSpacing: "0.18em", fontFamily: "'DM Sans', sans-serif", fontWeight: 700 }}>
            ⚠ {lang === "es" ? "PAGA AL RECOGER" : "PAY AT PICKUP"}
          </span>
        )}
        <span style={{ background: "transparent", color: "#F6F4EF", padding: "3px 8px", fontSize: 10, letterSpacing: "0.18em", border: "1px solid rgba(246,244,239,0.3)", fontFamily: "'DM Sans', sans-serif", fontWeight: 700 }}>
          ⏱ {order.pickupAt}
        </span>
      </div>

      {/* Items */}
      <div style={{ display: "flex", flexDirection: "column", gap: 6, padding: "8px 0", borderTop: "1px dashed rgba(246,244,239,0.15)" }}>
        {order.items.map((it, i) => (
          <div key={i} style={{ fontSize: 13, lineHeight: 1.45 }}>
            <div style={{ display: "flex", justifyContent: "space-between" }}>
              <span><b>{it.qty}×</b> {it.name}</span>
              <span style={{ fontFamily: "'Anton', sans-serif", color: "rgba(246,244,239,0.7)" }}>{fmtL(it.price * it.qty)}</span>
            </div>
            {it.sauces && it.sauces.length > 0 && (
              <div style={{ fontSize: 11, color: "#E63426", letterSpacing: "0.06em", marginTop: 2 }}>+ {it.sauces.join(" · ")}</div>
            )}
            {it.notes && (
              <div style={{ fontSize: 11, color: "#FFC107", fontStyle: "italic", marginTop: 2 }}>★ {it.notes}</div>
            )}
          </div>
        ))}
      </div>

      {/* Total */}
      <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "'Anton', sans-serif", fontSize: 18, letterSpacing: "0.04em" }}>
        <span>{lang === "es" ? "TOTAL" : "TOTAL"}</span>
        <span style={{ color: "#E63426" }}>{fmtL(order.total)}</span>
      </div>

      {/* Actions */}
      <div style={{ display: "flex", gap: 6, marginTop: 4 }}>
        {!isFirst && (
          <button onClick={onRegress} style={btnSmallStyle}>←</button>
        )}
        {!order.paid && (
          <button onClick={onMarkPaid} style={{ ...btnSmallStyle, flex: 1 }}>
            {lang === "es" ? "MARCAR PAGADO" : "MARK PAID"}
          </button>
        )}
        {!isLast && (
          <button onClick={onAdvance} style={{ ...btnSmallStyle, flex: 2, background: "#E63426", borderColor: "#E63426" }}>
            {KITCHEN_STAGES[KITCHEN_STAGES.findIndex(s => s.id === order.stage) + 1][lang].toUpperCase()} →
          </button>
        )}
      </div>
    </div>
  );
}

const btnSmallStyle = {
  appearance: "none",
  background: "transparent",
  border: "1px solid rgba(246,244,239,0.3)",
  color: "#F6F4EF",
  padding: "8px 10px",
  fontFamily: "'Anton', sans-serif",
  fontSize: 12,
  letterSpacing: "0.14em",
  cursor: "pointer",
  flex: 1,
};

window.ScreenKitchen = ScreenKitchen;
