// screens-tabs.jsx — keypad, contacts, recents

function normalizeHomeInput(raw) {
  let s = fromFa(String(raw == null ? "" : raw)).replace(/[^\d+]/g, "");
  if (!s) return "";
  if (s.startsWith("+98"))  return s.slice(0, 13);
  if (s.startsWith("0098")) return ("+98" + s.slice(4)).slice(0, 13);
  if (s.startsWith("98") && s.length > 10) return ("+98" + s.slice(2)).slice(0, 13);
  if (s.startsWith("0"))    return ("+98" + s.slice(1)).slice(0, 13);
  if (/^\d{10}$/.test(s))   return "+98" + s;
  return s;
}

function Keypad({ t, fa, onCall, onAddContact, onTopUp, balanceState, bannerMsg, prefilled }) {
  const [num, setNum] = React.useState(prefilled || "");
  const [clipMsg, setClipMsg] = React.useState("");
  const back = () => { setClipMsg(""); setNum((n) => n.slice(0, -1)); };
  const contactsSupported = typeof navigator !== "undefined" && navigator.contacts && typeof navigator.contacts.select === "function";
  const inputRef = React.useRef(null);

  const pasteFromClipboard = async () => {
    setClipMsg("");
    try {
      if (!navigator.clipboard || !navigator.clipboard.readText) throw new Error("unsupported");
      const text = await navigator.clipboard.readText();
      const norm = normalizeHomeInput(text);
      if (!norm) { setClipMsg(t.kp_paste_empty); return; }
      setNum(norm);
    } catch (e) { setClipMsg(t.kp_paste_err); }
  };

  const pickFromContacts = async () => {
    setClipMsg("");
    if (contactsSupported) {
      try {
        const picked = await navigator.contacts.select(["tel"], { multiple: false });
        const tel = picked && picked[0] && picked[0].tel && picked[0].tel[0];
        if (tel) { const norm = normalizeHomeInput(tel); if (norm) setNum(norm); }
      } catch (e) {}
    } else if (inputRef.current) {
      inputRef.current.setAttribute("autocomplete", "tel");
      inputRef.current.focus();
      setClipMsg(t.kp_pick_ios_hint);
    }
  };

  // home-country-format validation
  const v = validateHomeNumber(num);
  const canDial = v.valid;

  // Display formatter — home-country grouping: 3-3-4 after prefix
  const display = (() => {
    if (!num) return "";
    const s = fromFa(num).replace(/[^\d+]/g, "");
    let g = s;
    if (s.startsWith("+98")) g = `+98 ${s.slice(3,6)} ${s.slice(6,9)} ${s.slice(9,13)}`;
    else if (s.startsWith("0098")) g = `+98 ${s.slice(4,7)} ${s.slice(7,10)} ${s.slice(10,14)}`;
    else if (s.startsWith("0") && s.length >= 4) g = `0${s.slice(1,4)} ${s.slice(4,7)} ${s.slice(7,11)}`;
    else g = s;
    return (fa ? toFa(g) : g).trim();
  })();

  // Hint copy + tone
  let hint = "", tone = "default";
  if (!num) hint = t.kp_hint_empty;
  else if (v.valid) {
    hint = v.type === "mobile" ? t.kp_hint_mobile : v.type === "home" ? t.kp_hint_capital : t.kp_hint_landline;
    tone = "ok";
  } else if (v.reason === "long")           { hint = t.kp_err_long;    tone = "err"; }
  else if (v.reason === "unknown_prefix")   { hint = t.kp_err_unknown; tone = "err"; }
  else                                       { hint = t.kp_hint_typing; tone = "soft"; }

  return (
    <div className="kp-screen">
      <div className="kp-display">
        <input
          ref={inputRef}
          className={`kp-input ${tone === "err" ? "err" : ""}`}
          type="tel"
          inputMode="tel"
          value={display}
          placeholder={fa ? "۰۹۱۲ ۰۰۰ ۰۰۰۰" : "0912 000 0000"}
          onChange={(e) => { const norm = normalizeHomeInput(e.target.value); setNum(norm); }}
          autoComplete="off"
        />
        <div className={`kp-hint kp-hint-${tone}`}>{hint}</div>
      </div>
      <div className="kp-methods">
        <button className="kp-method primary" onClick={pasteFromClipboard}>
          <span className="mi"><Ico name="clipboard" size={20} /></span>{t.kp_paste}
        </button>
        <button className="kp-method" onClick={pickFromContacts}>
          <span className="mi"><Ico name="contacts" size={20} /></span>{t.kp_pick}
        </button>
        <div className="kp-clip-msg" role={clipMsg ? "alert" : undefined}>{clipMsg}</div>
      </div>
      <div className="kp-actions">
        <button className="side" onClick={() => onAddContact?.(v.e164 || num)} disabled={!canDial} style={{ opacity: canDial ? 1 : 0.3 }} aria-label={t.save_to_contacts}>
          <Ico name="user-plus" size={22} />
        </button>
        <button className="kp-call" onClick={() => canDial && onCall(v.e164)} disabled={!canDial}
          style={{ opacity: canDial ? 1 : 0.4, cursor: canDial ? "pointer" : "not-allowed" }} aria-label={t.call}>
          <Ico name="phone-fill" size={26} />
        </button>
        <button className="side" onClick={back} disabled={!num} style={{ opacity: num ? 1 : 0.3 }} aria-label="backspace">
          <Ico name="backspace" size={22} />
        </button>
      </div>
    </div>);

}

// ── Contacts ──────────────────────────────────────────────────────────
function Contacts({ t, fa, contacts, balanceState, bannerMsg, onCall, onEdit, onAdd, onTopUp }) {
  const hasContacts = contacts.length > 0;

  // group by initial letter
  const groups = {};
  contacts.forEach((c) => {
    const k = (c.name[0] || "?").toUpperCase();
    (groups[k] = groups[k] || []).push(c);
  });
  const letters = Object.keys(groups).sort();

  return (
    <div className="screen-tab">
      {balanceState === "empty" &&
      <div className="empty-state">
          <div className="illus">
            <svg width="80" height="80" viewBox="0 0 80 80" fill="none" stroke="currentColor" strokeWidth="1.4">
              <path d="M20 55c0-8 6-12 12-12h16c6 0 12 4 12 12" />
              <circle cx="40" cy="28" r="12" />
              <path d="M56 40l8-8M56 32l8 8" strokeWidth="1.6" opacity=".5" />
            </svg>
          </div>
          <h3 className="display">{t.zero_state_h}</h3>
          <p>{t.zero_state_p}</p>
          <button className="btn btn-primary" onClick={onTopUp}>{t.buy_time}</button>
        </div>
      }
      {bannerMsg && balanceState === "low" &&
      <div className="low-banner">
          <Ico name="alert" size={18} className="ico" />
          <div className="text">{bannerMsg}</div>
          <button onClick={onTopUp}>{t.top_up}</button>
        </div>
      }

      <div className="searchwrap">
        <div className="search">
          <Ico name="search" size={16} />
          <span>{t.search_placeholder}</span>
        </div>
      </div>

      {!hasContacts &&
      <div className="empty-state">
          <div className="illus">
            <svg width="80" height="80" viewBox="0 0 80 80" fill="none" stroke="currentColor" strokeWidth="1.4">
              <rect x="12" y="18" width="56" height="44" rx="6" />
              <circle cx="28" cy="36" r="6" />
              <path d="M18 56c2-6 6-8 10-8s8 2 10 8" />
              <path d="M44 32h18M44 40h14M44 48h10" strokeWidth="1.2" opacity=".6" />
            </svg>
          </div>
          <h3 className="display">{t.no_contacts_h}</h3>
          <p>{t.no_contacts_p}</p>
          <button className="btn btn-primary" onClick={() => onAdd()}>
            <Ico name="plus" size={16} /> {t.add_first}
          </button>
        </div>
      }

      {hasContacts &&
      <div className="scrollarea">
          {letters.map((L) =>
        <div key={L}>
              <div className="section-h">{L}</div>
              <div className="list">
                {groups[L].map((c) =>
            <div className="list-item" key={c.id} onClick={() => onCall(c)}>
                    <div className={`avatar ${c.tint || ""}`}>{c.initial || c.name[0]}</div>
                    <div className="body">
                      <div className="name">{c.name}</div>
                      <div className="meta">
                        <span className="mono">{c.numDisplay}</span>
                        {c.lastCalled && <> · {t.last_called(c.lastCalled)}</>}
                      </div>
                    </div>
                    <div className="right">
                      <button className="call-btn" onClick={(e) => {e.stopPropagation();onCall(c);}} aria-label="call">
                        <Ico name="phone-fill" size={14} />
                      </button>
                    </div>
                  </div>
            )}
              </div>
            </div>
        )}
          <div style={{ height: 8 }}></div>
          <div className="section-h">
            <span>{contacts.length} {fa ? "نفر" : "people"}</span>
          </div>
        </div>
      }
    </div>);

}

// ── Recents ───────────────────────────────────────────────────────────
function Recents({ t, fa, recents, balanceState, bannerMsg, onCall, onTopUp }) {
  if (recents.length === 0) {
    return (
      <div className="screen-tab" style={{ display: 'flex', flexDirection: 'column', flex: 1 }}>
        <div className="empty-state">
          <div className="illus">
            <svg width="80" height="80" viewBox="0 0 80 80" fill="none" stroke="currentColor" strokeWidth="1.4">
              <circle cx="40" cy="40" r="28" />
              <path d="M40 24v16l11 8" />
            </svg>
          </div>
          <h3 className="display">{t.no_recents_h}</h3>
          <p>{t.no_recents_p}</p>
        </div>
      </div>);

  }

  // group by section label
  const groups = {};
  recents.forEach((r) => {(groups[r.when] = groups[r.when] || []).push(r);});

  return (
    <div className="screen-tab">
      {bannerMsg && (balanceState === "low" || balanceState === "empty") &&
      <div className="low-banner">
          <Ico name="alert" size={18} className="ico" />
          <div className="text">{bannerMsg}</div>
          <button onClick={onTopUp}>{balanceState === "empty" ? t.buy_time : t.top_up}</button>
        </div>
      }
      <div className="scrollarea">
        {Object.entries(groups).map(([when, items]) =>
        <div key={when}>
            <div className="section-h">{when}</div>
            {items.map((r) =>
          <div key={r.id} className={`rec-item ${r.status === "cancelled" || r.status === "missed" ? "missed" : ""}`} onClick={() => onCall(r)}>
                <div className="ico">
                  <Ico name={r.dir === "out" ? "phone-outgoing" : r.status === "cancelled" || r.status === "missed" ? "phone-missed" : "phone-incoming"} size={18} />
                </div>
                <div className="body">
                  <div className={`name ${r.unknown ? "muted" : ""}`}>{r.name || r.numDisplay}</div>
                  <div className="meta">
                    {r.unknown ? <span className="mono">{r.numDisplay}</span> : <span>{r.numDisplay}</span>}
                    {r.status && r.status !== "completed" &&
                <span className={`pill ${r.status === "in-progress" ? "connecting" : r.status}`}>{r.status === "failed" ? (t["fail_short_" + failKey(r.failReason)] || t.failed) : (t[r.status] || r.status)}</span>
                }
                  </div>
                </div>
                <div className="time">{r.time}{r.duration ? <> · <span className="mono">{r.duration}</span></> : null}</div>
              </div>
          )}
          </div>
        )}
        <div style={{ height: 24 }}></div>
      </div>
    </div>);

}

window.Keypad = Keypad;
window.Contacts = Contacts;
window.Recents = Recents;
