/* global React, I, UI */
// =============== Global delivery alert — เด้งทุกหน้าจอ ตามความถี่ที่ user ตั้ง ===============
const { useState: useStateAl, useEffect: useEffectAl, useRef: useRefAl } = React;

const ALERT_FREQ_KEY = "sss-alert-freq-min";     // นาที (default 60)
const ALERT_NEXT_KEY = "sss-alert-next-ts";      // timestamp ของการเตือนครั้งถัดไป
const ALERT_OFF_KEY = "sss-alert-off-date";      // ปิดเตือนของวันนี้

const FREQ_OPTIONS = [
  { min: 15, label: "ทุก 15 นาที" },
  { min: 30, label: "ทุก 30 นาที" },
  { min: 60, label: "ทุก 1 ชั่วโมง" },
  { min: 120, label: "ทุก 2 ชั่วโมง" }
];

function getFreq() {
  const v = parseInt(localStorage.getItem(ALERT_FREQ_KEY) || "60", 10);
  return FREQ_OPTIONS.some(o => o.min === v) ? v : 60;
}
function setFreq(min) {
  localStorage.setItem(ALERT_FREQ_KEY, String(min));
  window.dispatchEvent(new Event("sss-alert-freq-changed"));
}
function freqLabel(min) {
  return (FREQ_OPTIONS.find(o => o.min === min) || {}).label || `ทุก ${min} นาที`;
}
function snooze(min) {
  localStorage.setItem(ALERT_NEXT_KEY, String(Date.now() + min * 60 * 1000));
}
function isMutedToday() {
  return localStorage.getItem(ALERT_OFF_KEY) === window.DeliveryStore.todayStr();
}

window.DeliveryAlertAPI = {
  getFreq, setFreq, freqLabel, FREQ_OPTIONS,
  // เรียกเมื่อเพิ่มงานส่งใหม่ → เด้งเตือนทุกหน้าจอทันที
  triggerNow() {
    localStorage.removeItem(ALERT_OFF_KEY);
    localStorage.setItem(ALERT_NEXT_KEY, "0");
    window.dispatchEvent(new Event("sss-alert-now"));
  },
  muteToday() {
    localStorage.setItem(ALERT_OFF_KEY, window.DeliveryStore.todayStr());
  }
};

function DeliveryAlertHost() {
  const { Btn, Badge } = window.UI;
  const [open, setOpen] = useStateAl(false);
  const [freq, setFreqState] = useStateAl(() => getFreq());
  const timerRef = useRefAl(null);

  const pendingToday = () => {
    const S = window.DeliveryStore;
    return S.load().filter(d => d.date === S.todayStr() && d.status !== "ส่งแล้ว");
  };

  const check = () => {
    if (document.body.classList.contains("printing-modal")) return; // อย่าเด้งทับหน้าพิมพ์
    if (isMutedToday()) return;
    const pending = pendingToday();
    if (pending.length === 0) return;
    const next = parseInt(localStorage.getItem(ALERT_NEXT_KEY) || "0", 10);
    if (Date.now() >= next) setOpen(true);
  };

  useEffectAl(() => {
    const t = setTimeout(check, 1200);                  // เตือนครั้งแรกหลังเปิดหน้าจอ
    timerRef.current = setInterval(check, 20 * 1000);   // เช็คทุก 20 วิ เทียบเวลาเตือนถัดไป
    const onNow = () => { setOpen(false); setTimeout(() => check(), 300); };
    const onFreq = () => setFreqState(getFreq());
    window.addEventListener("sss-alert-now", onNow);
    window.addEventListener("sss-alert-freq-changed", onFreq);
    return () => {
      clearTimeout(t);
      clearInterval(timerRef.current);
      window.removeEventListener("sss-alert-now", onNow);
      window.removeEventListener("sss-alert-freq-changed", onFreq);
    };
  }, []);

  if (!open) return null;

  const pending = pendingToday();
  if (pending.length === 0) { snooze(freq); if (open) setTimeout(() => setOpen(false), 0); return null; }

  const ack = () => { snooze(freq); setOpen(false); };
  const mute = () => { window.DeliveryAlertAPI.muteToday(); setOpen(false); window.toast && window.toast("ปิดเตือนของวันนี้แล้ว"); };
  const go = () => { ack(); window.location.hash = "#/daily-delivery"; };
  const pickFreq = (min) => { setFreq(min); setFreqState(min); snooze(min); };

  return (
    <div className="scrim" style={{display: "flex", alignItems: "center", justifyContent: "center", padding: 24, zIndex: 260}}>
      <div style={{background: "var(--surface)", borderRadius: 14, width: 580, maxWidth: "94vw", maxHeight: "90vh", overflow: "auto", boxShadow: "var(--shadow-lg)", border: "1px solid var(--line-strong)"}}>
        <div style={{padding: "18px 22px 14px", borderBottom: "1px solid var(--line)", background: "linear-gradient(to right, var(--warning-bg), transparent)", display: "flex", alignItems: "center", gap: 12}}>
          <div style={{width: 40, height: 40, borderRadius: 10, background: "var(--warning)", color: "white", display: "grid", placeItems: "center", flexShrink: 0}}>
            <I.bell size={20}/>
          </div>
          <div style={{flex: 1, minWidth: 0}}>
            <div style={{fontSize: 16, fontWeight: 700}}>วันนี้มีของต้องส่ง — เหลือ {pending.length} รายการ</div>
            <div style={{fontSize: 12, color: "var(--ink-3)"}}>เตือนอัตโนมัติ{freqLabel(freq)} จนกว่าจะส่งครบ · ปรับความถี่ได้ด้านล่าง</div>
          </div>
          <button className="icon-btn" onClick={ack} title="รับทราบ"><I.close size={14}/></button>
        </div>

        <div style={{padding: 16, display: "flex", flexDirection: "column", gap: 8}}>
          {pending.map(d => (
            <div key={d.id} style={{padding: "10px 12px", border: "1px solid var(--line)", borderRadius: 8, borderLeft: "4px solid var(--warning)", display: "flex", gap: 12, alignItems: "center"}}>
              <div style={{minWidth: 48, textAlign: "center", flexShrink: 0}}>
                <div style={{fontSize: 16, fontWeight: 700}}>{d.time}</div>
                <div style={{fontSize: 9.5, color: "var(--ink-3)"}}>นัดส่ง</div>
              </div>
              <div style={{flex: 1, minWidth: 0}}>
                <div style={{display: "flex", gap: 8, alignItems: "center"}}>
                  <span style={{fontWeight: 600, fontSize: 13}}>{d.customer}</span>
                  <Badge>{d.status}</Badge>
                </div>
                <div style={{fontSize: 11.5, color: "var(--ink-3)", marginTop: 2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"}}>
                  {(d.items || []).map(i => `${i.qty} ${i.unit} ${i.name}`).join(" · ")}
                </div>
              </div>
              <div style={{fontSize: 11, color: "var(--ink-3)", flexShrink: 0}}>{d.assigneeName}</div>
            </div>
          ))}

          <div style={{marginTop: 6, padding: "10px 12px", background: "var(--surface-2)", borderRadius: 8, display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap"}}>
            <span style={{fontSize: 12, fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 6}}><I.clock size={13}/>เตือนซ้ำ:</span>
            <div style={{display: "flex", gap: 4, flexWrap: "wrap"}}>
              {FREQ_OPTIONS.map(o => (
                <button key={o.min} className={`btn sm ${freq === o.min ? "primary" : ""}`} onClick={() => pickFreq(o.min)}>{o.label}</button>
              ))}
            </div>
          </div>
        </div>

        <div style={{padding: "12px 16px", borderTop: "1px solid var(--line)", background: "var(--surface-2)", display: "flex", gap: 8, justifyContent: "space-between", flexWrap: "wrap"}}>
          <Btn kind="ghost" onClick={mute}>ไม่แสดงอีกในวันนี้</Btn>
          <div style={{display: "flex", gap: 8}}>
            <Btn onClick={ack}>รับทราบ (เตือนอีก{freqLabel(freq).replace("ทุก ", "ใน ")})</Btn>
            <Btn kind="primary" icon={I.truck} onClick={go}>ไปหน้าส่งของ</Btn>
          </div>
        </div>
      </div>
    </div>
  );
}

window.DeliveryAlertHost = DeliveryAlertHost;
