/* Relay — main app */
const { useState, useEffect, useRef, useMemo } = React;
const RD = window.RelayData;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "layout": "columns",
  "density": "regular",
  "accent": "#2563EB",
  "showKpis": true,
  "feedSpeed": "normal"
}/*EDITMODE-END*/;

// short two-tone chime via WebAudio
function makeChime() {
  let ctx = null;
  return function play() {
    try {
      ctx = ctx || new (window.AudioContext || window.webkitAudioContext)();
      if (ctx.state === "suspended") ctx.resume();
      const now = ctx.currentTime;
      [ [880, 0], [1320, 0.12] ].forEach(([f, t]) => {
        const o = ctx.createOscillator(), g = ctx.createGain();
        o.type = "sine"; o.frequency.value = f;
        g.gain.setValueAtTime(0.0001, now + t);
        g.gain.exponentialRampToValueAtTime(0.22, now + t + 0.02);
        g.gain.exponentialRampToValueAtTime(0.0001, now + t + 0.32);
        o.connect(g).connect(ctx.destination);
        o.start(now + t); o.stop(now + t + 0.34);
      });
    } catch (e) {}
  };
}

function Notices({ notices }) {
  return (
    <div style={{ position: "fixed", bottom: 22, left: "50%", transform: "translateX(-50%)", zIndex: 85, display: "flex", flexDirection: "column", gap: 8, alignItems: "center" }}>
      {notices.map((n) => (
        <div key={n.id} style={{ background: "var(--graphite)", color: "#fff", fontSize: 13, fontWeight: 500, padding: "11px 18px", borderRadius: 999, boxShadow: "var(--shadow-lg)", display: "flex", alignItems: "center", gap: 9, animation: "dropIn .25s" }}>
          <span style={{ width: 7, height: 7, borderRadius: 999, background: "var(--ready)" }} />
          {n.text}
        </div>
      ))}
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [orders, setOrders] = useState(() => RD.seedOrders());
  const [branch, setBranch] = useState(RD.BRANCHES[0]);
  const [soundOn, setSoundOn] = useState(true);
  const [typeFilter, setTypeFilter] = useState("all");
  const [platFilter, setPlatFilter] = useState([]);
  const [statusFilter, setStatusFilter] = useState("active");
  const [search, setSearch] = useState("");
  const [simOn, setSimOn] = useState(true);
  const [selectedId, setSelectedId] = useState(null);
  const [toasts, setToasts] = useState([]);
  const [now, setNow] = useState(Date.now());
  const [view, setView] = useState("dashboard");
  const [history] = useState(() => RD.seedHistory(7));
  const [notices, setNotices] = useState([]);
  const chime = useRef(makeChime());

  const allOrders = useMemo(() => [...orders, ...history], [orders, history]);

  // global text-toast helper (used by Reports export, Integrations connect, POS)
  useEffect(() => {
    window.__relayToast = (text) => {
      const id = "n" + Date.now() + Math.random();
      setNotices((p) => [{ id, text }, ...p].slice(0, 3));
      setTimeout(() => setNotices((p) => p.filter((x) => x.id !== id)), 3200);
    };
    return () => { delete window.__relayToast; };
  }, []);

  const layout = t.layout;
  const dense = t.density === "compact";

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

  // accent → CSS var
  useEffect(() => {
    document.documentElement.style.setProperty("--accent", t.accent);
    document.documentElement.style.setProperty("--new", t.accent);
  }, [t.accent]);

  // live simulation
  useEffect(() => {
    if (!simOn) return;
    const base = t.feedSpeed === "fast" ? 4500 : t.feedSpeed === "slow" ? 14000 : 8000;
    let timer;
    const schedule = () => {
      const jitter = base * (0.6 + Math.random() * 0.8);
      timer = setTimeout(() => {
        addIncoming();
        schedule();
      }, jitter);
    };
    schedule();
    return () => clearTimeout(timer);
  }, [simOn, t.feedSpeed]);

  function addIncoming() {
    const o = RD.buildOrder({ status: "new", minutesAgo: 0 });
    o._flash = true;
    setOrders((prev) => [o, ...prev].slice(0, 80));
    if (soundOn) chime.current();
    setToasts((prev) => [{ id: o.id, order: o }, ...prev].slice(0, 4));
    setTimeout(() => setToasts((prev) => prev.filter((x) => x.id !== o.id)), 5200);
    setTimeout(() => setOrders((prev) => prev.map((x) => x.id === o.id ? { ...x, _flash: false } : x)), 600);
  }

  // mutations
  const patch = (id, fields) => setOrders((prev) => prev.map((o) => o.id === id ? { ...o, ...fields } : o));
  const onAccept = (o) => patch(o.id, { status: "preparing", acceptedAt: Date.now(), isNew: false });
  const onReject = (o) => patch(o.id, { status: "cancelled", isNew: false });
  const onAdvance = (o) => {
    const next = o.status === "preparing" ? "ready" : o.status === "ready" ? "completed" : o.status;
    patch(o.id, { status: next });
  };
  const onOpen = (o) => setSelectedId(o.id);

  // filtering
  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    return orders.filter((o) => {
      if (typeFilter !== "all" && o.type !== typeFilter) return false;
      if (platFilter.length && !platFilter.includes(o.platformId)) return false;
      if (q) {
        const hay = (o.customer + " " + o.id + " " + o.channelRef + " " + PLATFORMS[o.platformId].name + " " + o.items.map((i) => i.name).join(" ")).toLowerCase();
        if (!hay.includes(q)) return false;
      }
      return true;
    });
  }, [orders, typeFilter, platFilter, search]);

  // status filter only for list/grid
  const listFiltered = useMemo(() => {
    return filtered.filter((o) => {
      if (statusFilter === "all") return true;
      if (statusFilter === "active") return ["new", "preparing", "ready"].includes(o.status);
      if (statusFilter === "preparing") return ["preparing", "ready"].includes(o.status);
      return o.status === statusFilter;
    }).sort((a, b) => b.placedAt - a.placedAt);
  }, [filtered, statusFilter]);

  // counts / KPIs
  const counts = useMemo(() => {
    const c = { new: 0, preparing: 0, ready: 0, completed: 0, late: 0, revenue: 0, total: 0 };
    orders.forEach((o) => {
      if (c[o.status] !== undefined) c[o.status]++;
      if (o.status !== "cancelled") { c.total++; c.revenue += o.total; }
      const base = o.acceptedAt || o.placedAt;
      if (["new", "preparing", "ready"].includes(o.status) && (now - base) / 60000 >= o.prepMins) c.late++;
    });
    return c;
  }, [orders, now]);

  const selected = allOrders.find((o) => o.id === selectedId) || null;
  const cardProps = { now, onOpen, onAccept, onReject, onAdvance, dense };

  // place a manual (phone/POS) order into the live pipeline
  function placeManual(order) {
    order._flash = true;
    setOrders((prev) => [order, ...prev].slice(0, 80));
    if (soundOn) chime.current();
    window.__relayToast && window.__relayToast(`${order.id} nolu sipariş alındı — ${order.type === "food" ? "mutfağa" : "hazırlama birimine"} gönderildi.`);
    setTimeout(() => setOrders((prev) => prev.map((x) => x.id === order.id ? { ...x, _flash: false } : x)), 600);
    setView("dashboard");
  }

  // ---------- layouts ----------
  function renderList() {
    return (
      <div style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--radius)", overflow: "hidden", boxShadow: "var(--shadow-sm)" }}>
        <div style={{ display: "grid", gridTemplateColumns: "150px 110px 1fr 70px 130px 140px 210px", gap: 14, padding: "10px 16px 10px 16px", borderBottom: "1px solid var(--border)", background: "var(--surface-2)", fontSize: 10.5, fontWeight: 600, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".05em" }}>
          <span>Platform</span><span>Ref</span><span>Müşteri</span><span style={{ textAlign: "center" }}>Ürün</span><span>Toplam</span><span>Durum</span><span style={{ textAlign: "right" }}>İşlem</span>
        </div>
        {listFiltered.length === 0 ? emptyState() :
          listFiltered.map((o) => <OrderRow key={o.id} order={o} {...cardProps} />)}
      </div>
    );
  }
  function renderGrid() {
    if (listFiltered.length === 0) return <div style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--radius)" }}>{emptyState()}</div>;
    return (
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(290px, 1fr))", gap: 14, alignContent: "start" }}>
        {listFiltered.map((o) => <OrderCard key={o.id} order={o} {...cardProps} />)}
      </div>
    );
  }
  function renderColumns() {
    const cols = RD.statusOrder.map((k) => ({
      key: k, label: FLOW_LABELS.food[k] === FLOW_LABELS.retail[k] ? STATUS[k].label : STATUS[k].label,
      items: filtered.filter((o) => o.status === k).sort((a, b) => b.placedAt - a.placedAt),
    }));
    return (
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, height: "100%", minHeight: 0 }}>
        {cols.map((col) => (
          <div key={col.key} style={{ display: "flex", flexDirection: "column", minHeight: 0, background: "var(--surface-3)", borderRadius: "var(--radius)", border: "1px solid var(--border)" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "11px 13px", borderBottom: "1px solid var(--border)" }}>
              <span style={{ display: "flex", alignItems: "center", gap: 8, fontWeight: 600, fontSize: 13.5 }}>
                <span style={{ width: 9, height: 9, borderRadius: 999, background: STATUS[col.key].color }} />
                {STATUS[col.key].label}
              </span>
              <span className="mono" style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-2)", background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 999, padding: "1px 9px" }}>{col.items.length}</span>
            </div>
            <div style={{ flex: 1, overflowY: "auto", padding: 10, display: "flex", flexDirection: "column", gap: 10 }}>
              {col.items.length === 0
                ? <div style={{ textAlign: "center", color: "var(--text-3)", fontSize: 12.5, padding: "24px 0" }}>Sipariş yok</div>
                : col.items.map((o) => <OrderCard key={o.id} order={o} {...cardProps} dense />)}
            </div>
          </div>
        ))}
      </div>
    );
  }
  function emptyState() {
    return (
      <div style={{ padding: "56px 20px", textAlign: "center", color: "var(--text-3)" }}>
        <div style={{ display: "inline-flex", width: 48, height: 48, borderRadius: 12, background: "var(--surface-3)", alignItems: "center", justifyContent: "center", marginBottom: 12, color: "var(--text-3)" }}><I.orders size={22} /></div>
        <div style={{ fontWeight: 600, fontSize: 14, color: "var(--text-2)" }}>Filtrelere uygun sipariş bulunamadı</div>
        <div style={{ fontSize: 12.5, marginTop: 3 }}>Platform veya durum filtrelerini temizlemeyi deneyin.</div>
      </div>
    );
  }

  return (
    <div style={{ display: "flex", height: "100vh", overflow: "hidden" }}>
      <NavRail view={view} setView={setView} />

      {view === "pos" ? (
        <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column" }}>
          <POSScreen branch={branch} onPlace={placeManual} onCancel={() => setView("dashboard")} />
        </div>
      ) : (
        <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
          <TopBar {...{ branch, setBranch, soundOn, setSoundOn, now, newCount: counts.new, search, setSearch, showSearch: view === "dashboard" }} />

          {view === "dashboard" && <>
            <Toolbar {...{
              typeFilter, setTypeFilter,
              platFilter, togglePlat: (id) => setPlatFilter((p) => p.includes(id) ? p.filter((x) => x !== id) : [...p, id]), clearPlat: () => setPlatFilter([]),
              statusFilter, setStatusFilter, layout, setLayout: (l) => setTweak("layout", l),
              simOn, setSimOn, counts,
            }} />

            {t.showKpis && (
              <div style={{ display: "flex", gap: 12, padding: "14px 20px 0" }}>
                <Kpi label="Yeni" value={counts.new} accent="var(--new)" icon={<I.bolt size={13} />} sub="bekliyor" />
                <Kpi label="Hazırlanıyor" value={counts.preparing + counts.ready} icon={<I.refresh size={13} />} sub={`${counts.ready} hazır`} />
                <Kpi label="Geciken" value={counts.late} accent={counts.late ? "var(--cancelled)" : "var(--text)"} icon={<I.clock size={13} />} />
                <Kpi label="Bugünkü Siparişler" value={counts.total} icon={<I.receipt size={13} />} />
                <Kpi label="Bugünkü Ciro" value={"AED " + Math.round(counts.revenue).toLocaleString()} icon={<I.reports size={13} />} />
              </div>
            )}

            <main style={{ flex: 1, minHeight: 0, padding: "16px 20px 20px", overflowY: layout === "columns" ? "hidden" : "auto" }}>
              {layout === "list" && renderList()}
              {layout === "grid" && renderGrid()}
              {layout === "columns" && renderColumns()}
            </main>
          </>}

          {view === "orders" && <AllOrdersScreen allOrders={allOrders} now={now} onOpen={(o) => setSelectedId(o.id)} />}
          {view === "reports" && <ReportsScreen allOrders={allOrders} now={now} />}
          {view === "catalog" && <CatalogScreen />}
          {view === "integrations" && <IntegrationsScreen />}
        </div>
      )}

      <DetailPanel order={selected} now={now} onClose={() => setSelectedId(null)} onAccept={onAccept} onReject={onReject} onAdvance={onAdvance} />
      <Toasts toasts={toasts} onClick={(o) => { setView("dashboard"); setSelectedId(o.id); setToasts([]); }} />
      <Notices notices={notices} />

      <TweaksPanel>
        <TweakSection label="Düzen" />
        <TweakRadio label="Pano görünümü" value={t.layout} options={[{ value: "list", label: "Liste" }, { value: "grid", label: "Izgara" }, { value: "columns", label: "Sütunlar" }]} onChange={(v) => setTweak("layout", v)} />
        <TweakRadio label="Yoğunluk" value={t.density} options={[{ value: "compact", label: "Sıkışık" }, { value: "regular", label: "Normal" }]} onChange={(v) => setTweak("density", v)} />
        <TweakToggle label="KPI şeridini göster" value={t.showKpis} onChange={(v) => setTweak("showKpis", v)} />
        <TweakSection label="Canlı akış" />
        <TweakRadio label="Sipariş sıklığı" value={t.feedSpeed} options={[{ value: "slow", label: "Yavaş" }, { value: "normal", label: "Normal" }, { value: "fast", label: "Hızlı" }]} onChange={(v) => setTweak("feedSpeed", v)} />
        <TweakSection label="Tema" />
        <TweakColor label="Vurgu rengi" value={t.accent} options={["#2563EB", "#0F766E", "#7A4DF5", "#DB2777"]} onChange={(v) => setTweak("accent", v)} />
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
