// screens-notify.jsx — Status pill + schedule sheet + upcoming list
// Honest about the system: we only know two things about a call's progress —
// (1) it's queued (we're about to dial), (2) it's done (Android reported back).
// No fake "ringing now" — the gateway is offline most of the time.

const N_useS = React.useState;
const N_useE = React.useEffect;

// ── Status pill ───────────────────────────────────────────────────────
// Sits between the topbar and the scrollable content. Persists across tabs.
// `pill` = { id, kind, contact, durationSec, scheduledAt, retryUntil } | null
// fail_reason -> strings key suffix
function failKey(r) {
  if (["a_busy", "a_no_answer", "b_busy", "b_no_answer", "expired", "timeout"].includes(r)) return r;
  if (["a_failed", "b_failed", "no_port", "aborted"].includes(r)) return "connect";
  return "unknown";
}
function StatusPill({ pill, t, fa, onCancel, onDismiss, onRetry }) {
  if (!pill) return null;

  const k = pill.kind; // "queued" | "scheduled" | "completed" | "missed"
  const name = pill.contact?.name || "—";

  let title, sub, icon, accent, actions = null;
  if (k === "queued") {
    title = pill.retrying ? t.notify_retrying_title : t.notify_queued_title(name);
    sub   = pill.retrying ? t.notify_retrying_sub
          : pill.expireMinutes ? t.notify_queued_expire_sub(pill.expireMinutes)
          : t.notify_queued_sub;
    icon  = "phone-fill";
    accent = "saffron";
    // Only a call still waiting in the queue can be cancelled (user chose to, e.g. after a 409).
    actions = pill.cancellable ? <button className="pill-act" onClick={onCancel}>{t.notify_cancel}</button> : null;
  } else if (k === "in-progress") {
    title = t.notify_queued_title(name);
    sub   = t.notify_inprogress_sub;
    icon  = "phone-fill";
    accent = "saffron";
  } else if (k === "failed") {
    title = t.notify_failed_title(name);
    sub   = (t["fail_" + failKey(pill.reason)] || t.fail_unknown) + ". " + t.notify_no_charge;
    icon  = "alert";
    accent = "ember";
    actions = (
      <>
        <button className="pill-act ghost" onClick={onDismiss}>{t.notify_dismiss}</button>
        <button className="pill-act primary" onClick={onRetry}>{t.notify_retry}</button>
      </>
    );
  } else if (k === "scheduled") {
    title = t.notify_scheduled_title(name);
    sub   = t.notify_scheduled_sub(pill.scheduledLabel || "");
    icon  = "queue";
    accent = "ink";
    actions = (
      <button className="pill-act" onClick={onCancel}>{t.notify_cancel}</button>
    );
  } else if (k === "completed") {
    title = t.notify_completed_title(name);
    sub   = t.notify_completed_sub(pill.durationLabel || "—");
    icon  = "check";
    accent = "success";
    actions = (
      <button className="pill-act" onClick={onDismiss}>{t.notify_dismiss}</button>
    );
  } else if (k === "missed") {
    title = t.notify_missed_title(name);
    sub   = t.notify_missed_sub;
    icon  = "alert";
    accent = "ember";
    actions = (
      <>
        <button className="pill-act ghost" onClick={onDismiss}>{t.notify_dismiss}</button>
        <button className="pill-act primary" onClick={onRetry}>{t.notify_retry}</button>
      </>
    );
  }

  return (
    <div className={`status-pill pill-${accent}`} role="status" aria-live="polite">
      <div className="pill-ico"><Ico name={icon} size={18} /></div>
      <div className="pill-body">
        <div className="pill-title">{title}</div>
        <div className="pill-sub">{sub}</div>
      </div>
      <div className="pill-actions">{actions}</div>
    </div>
  );
}

// ── Schedule action sheet (small popup when tapping a contact row) ───
function ContactActionSheet({ contact, t, fa, onCallNow, onSchedule, onEdit, onClose }) {
  if (!contact) return null;
  return (
    <div className="action-sheet-backdrop" onClick={onClose}>
      <div className="action-sheet" onClick={(e) => e.stopPropagation()}>
        <div className="action-sheet-head">
          <div className={`avatar ${contact.tint || ""}`}>{contact.initial || contact.name?.[0] || "?"}</div>
          <div className="action-sheet-name">
            <div className="name">{contact.name}</div>
            <div className="num mono">{contact.numDisplay || contact.phone}</div>
          </div>
        </div>
        <div className="action-sheet-rows">
          <button className="ash-row primary" onClick={() => onCallNow(contact)}>
            <Ico name="phone-fill" size={18} />
            <span>{t.action_sheet_call_now}</span>
          </button>
          <button className="ash-row" onClick={() => onSchedule(contact)}>
            <Ico name="queue" size={18} />
            <span>{t.action_sheet_schedule}</span>
          </button>
          <button className="ash-row" onClick={() => onEdit(contact)}>
            <Ico name="edit" size={18} />
            <span>{t.action_sheet_edit}</span>
          </button>
        </div>
        <button className="ash-cancel" onClick={onClose}>{t.cancel}</button>
      </div>
    </div>
  );
}

// ── Schedule sheet (full overlay) ─────────────────────────────────────
function ScheduleSheet({ contact, t, fa, contacts, onClose, onConfirm }) {
  const [picked, setPicked] = N_useS(contact || null);
  const [retry, setRetry] = N_useS("once"); // once | keep

  // The "alarm-clock" picker — fully user-driven, no presets.
  // Initial: now + 30 min, rounded to nearest 5 min.
  const initialDate = N_useS(() => {
    const d = new Date();
    d.setMinutes(d.getMinutes() + 30);
    d.setMinutes(Math.round(d.getMinutes() / 5) * 5, 0, 0);
    return d;
  })[0];
  const [hour, setHour] = N_useS(initialDate.getHours());        // 0–23
  const [min, setMin]   = N_useS(initialDate.getMinutes());      // 0–59 (step 5)
  const [dayOff, setDayOff] = N_useS(initialDate.toDateString() === new Date().toDateString() ? 0 : 1);

  // Build the actual scheduled Date object
  const pickedDate = (() => {
    const d = new Date();
    d.setDate(d.getDate() + dayOff);
    d.setHours(hour, min, 0, 0);
    return d;
  })();

  // Quick +N chips — these write into the picker (not separate state)
  const applyQuick = (mins) => {
    const d = new Date();
    d.setMinutes(d.getMinutes() + mins);
    d.setMinutes(Math.round(d.getMinutes() / 5) * 5, 0, 0);
    setHour(d.getHours());
    setMin(d.getMinutes());
    setDayOff(d.toDateString() === new Date().toDateString() ? 0 : 1);
  };

  const now = new Date();
  const maxDate = new Date(now.getTime() + 24 * 3600 * 1000);
  const overLimit = pickedDate > maxDate;
  const inPast = pickedDate <= now;
  const canConfirm = picked && !overLimit && !inPast;

  // Relative time preview
  const diffMin = Math.max(0, Math.round((pickedDate - now) / 60000));
  const diffH = Math.floor(diffMin / 60);
  const diffM = diffMin % 60;
  const relText = diffH > 0 ? t.schedule_in_h(diffH, diffM) : t.schedule_in_m(diffM);

  // Absolute time label (HH:MM, today/tomorrow)
  const hh = String(pickedDate.getHours()).padStart(2, "0");
  const mm = String(pickedDate.getMinutes()).padStart(2, "0");
  const timeLabel = fa ? toFa(`${hh}:${mm}`) : `${hh}:${mm}`;
  const dayLabel = dayOff === 0
    ? (fa ? "امروز" : "today")
    : (fa ? "فردا" : "tomorrow");

  // Hour/minute steppers
  const bumpHour = (delta) => {
    let h = hour + delta;
    let off = dayOff;
    if (h < 0) { h = 23; off = Math.max(0, off - 1); }
    else if (h > 23) { h = 0; off = Math.min(1, off + 1); }
    setHour(h); setDayOff(off);
  };
  const bumpMin = (delta) => {
    let m = min + delta;
    if (m < 0) { m = 55; bumpHour(-1); }
    else if (m > 55) { m = 0; bumpHour(1); }
    setMin(m);
  };

  const handleConfirm = () => {
    onConfirm({
      contact: picked,
      scheduledAt: pickedDate,
      isNow: false,
      retry,
      retryUntil: retry === "keep" ? new Date(pickedDate.getTime() + 5 * 60000) : null
    });
  };

  return (
    <div className="buy" style={{paddingTop: 18}}>
      <div className="head">
        <h2 className="display">{t.schedule_h}</h2>
        <button className="close" onClick={onClose} aria-label="close"><Ico name="x" size={20} /></button>
      </div>
      <div className="lead">{t.schedule_sub}</div>

      {/* Contact picker */}
      <div className="sched-section">
        <div className="sched-label">{t.schedule_who}</div>
        {picked ? (
          <button className="sched-contact-picked" onClick={() => setPicked(null)}>
            <div className={`avatar ${picked.tint || ""}`}>{picked.initial || picked.name?.[0]}</div>
            <div className="who">
              <div className="name">{picked.name}</div>
              <div className="num mono">{picked.numDisplay || picked.phone}</div>
            </div>
            <Ico name={fa ? "chev-left" : "chev-right"} size={16} />
          </button>
        ) : (
          <div className="sched-contact-list">
            {contacts.slice(0, 5).map(c => (
              <button key={c.id} className="sched-contact-row" onClick={() => setPicked(c)}>
                <div className={`avatar ${c.tint || ""}`}>{c.initial || c.name?.[0]}</div>
                <div className="who">
                  <div className="name">{c.name}</div>
                  <div className="num mono">{c.numDisplay || c.phone}</div>
                </div>
              </button>
            ))}
          </div>
        )}
      </div>

      {/* Quick chips */}
      <div className="sched-section">
        <div className="sched-label">{t.schedule_when}</div>
        <div className="sched-chips" style={{gridTemplateColumns: "repeat(3, 1fr)"}}>
          <button className="sched-chip" onClick={() => applyQuick(30)}>{t.schedule_30m}</button>
          <button className="sched-chip" onClick={() => applyQuick(60)}>{t.schedule_1h}</button>
          <button className="sched-chip" onClick={() => applyQuick(120)}>{t.schedule_2h}</button>
        </div>

        {/* Alarm-clock picker */}
        <div className="time-picker" dir="ltr">
          <div className="tp-col">
            <button className="tp-arrow" onClick={() => bumpHour(1)} aria-label="hour up"><Ico name="chev-down" size={18} stroke={2} /></button>
            <div className="tp-val">{fa ? toFa(String(hour).padStart(2,"0")) : String(hour).padStart(2,"0")}</div>
            <button className="tp-arrow" onClick={() => bumpHour(-1)} aria-label="hour down"><Ico name="chev-down" size={18} stroke={2} /></button>
            <div className="tp-lbl">{t.schedule_hours}</div>
          </div>
          <div className="tp-sep">:</div>
          <div className="tp-col">
            <button className="tp-arrow" onClick={() => bumpMin(5)} aria-label="minute up"><Ico name="chev-down" size={18} stroke={2} /></button>
            <div className="tp-val">{fa ? toFa(String(min).padStart(2,"0")) : String(min).padStart(2,"0")}</div>
            <button className="tp-arrow" onClick={() => bumpMin(-5)} aria-label="minute down"><Ico name="chev-down" size={18} stroke={2} /></button>
            <div className="tp-lbl">{t.schedule_minutes}</div>
          </div>
        </div>

        <div className="sched-picked-time">
          {t.schedule_will_call}: <b>{dayLabel} · {timeLabel}</b>
          <span className="sched-limit">
            {overLimit
              ? (fa ? "بیش از ۲۴ ساعت دیگر — مجاز نیست" : "Beyond 24 hours — not allowed")
              : inPast
                ? (fa ? "گذشته است — جلوتر برو" : "In the past — pick a later time")
                : <>· {relText} · {t.schedule_24h_limit}</>
            }
          </span>
        </div>
      </div>

      {/* Retry policy */}
      <div className="sched-section">
        <div className="sched-label">{t.schedule_retry_label}</div>
        <div className="sched-radio-row">
          <button className={`sched-radio ${retry === "once" ? "on" : ""}`} onClick={() => setRetry("once")}>
            <span className="dot"></span>{t.schedule_retry_once}
          </button>
          <button className={`sched-radio ${retry === "keep" ? "on" : ""}`} onClick={() => setRetry("keep")}>
            <span className="dot"></span>{t.schedule_retry_keep}
          </button>
        </div>
      </div>

      <div className="actions">
        <button className="btn btn-primary btn-block btn-lg"
                onClick={handleConfirm}
                disabled={!canConfirm}>
          <Ico name="queue" size={16} /> {t.schedule_cta}
        </button>
      </div>
    </div>
  );
}

// ── Upcoming section (top of Recents) ─────────────────────────────────
function UpcomingSection({ items, t, fa, onCancel }) {
  if (!items || items.length === 0) return null;
  return (
    <div className="upcoming">
      <div className="section-h">{t.upcoming_h}</div>
      <div className="list">
        {items.map((u) => (
          <div className="upcoming-row" key={u.id}>
            <div className={`avatar ${u.tint || ""}`}>{u.initial || u.name?.[0] || "?"}</div>
            <div className="body">
              <div className="name">{u.name}</div>
              <div className="meta">{u.whenLabel}{u.retry === "keep" ? <> · <span className="rt">{t.schedule_retry_keep}</span></> : null}</div>
            </div>
            <button className="upcoming-cancel" onClick={() => onCancel(u)}>{t.upcoming_cancel}</button>
          </div>
        ))}
      </div>
    </div>
  );
}

window.StatusPill = StatusPill;
window.ContactActionSheet = ContactActionSheet;
window.ScheduleSheet = ScheduleSheet;
window.UpcomingSection = UpcomingSection;
