// myesims.jsx — view & activate purchased eSIMs (data from /api/my-esims)
const { useState: useStateE, useEffect: useEffectE, useRef: useRefE } = React;
const PENDING_ESIM_INSTALL_KEY = "journey-pending-esim-install";

function fmtData(mb) {
  if (mb === null || mb === undefined || Number.isNaN(Number(mb))) return "0 MB";
  return mb >= 1024 ? (mb / 1024).toFixed(mb % 1024 === 0 ? 0 : 1) + " GB" : mb + " MB";
}

function esimNetworkLabel(esim) {
  const net = String(esim?.net || "").trim();
  if (net && !/^4g\/5g$/i.test(net)) return net;
  const carriers = String(esim?.carriers || "").trim();
  if (carriers && !/^\d+\s+(country|countries|destination|destinations)$/i.test(carriers)) return carriers;
  return "Partner networks";
}

function QRGlyph({ uid }) {
  // Deterministic 7×7 QR-style grid seeded from the eSIM uid
  const seed = uid ? uid.split("").reduce((a, c) => a + c.charCodeAt(0), 0) : 0;
  const cells = Array.from({ length: 49 }, (_, i) => {
    // Always-on corner finder patterns
    const row = Math.floor(i / 7), col = i % 7;
    if ((row < 2 && col < 2) || (row < 2 && col > 4) || (row > 4 && col < 2)) return 1;
    return ((seed * (i + 1) * 7919) % 101) > 48 ? 1 : 0;
  });
  return (
    <div style={{ width: 132, height: 132, padding: 10, background: "#fff", borderRadius: 14,
      display: "grid", gridTemplateColumns: "repeat(7,1fr)", gap: 2 }}>
      {cells.map((c, i) => (
        <div key={i} style={{ background: c ? "#0a0a12" : "transparent", borderRadius: 1 }}></div>
      ))}
    </div>
  );
}

function esimStatusMeta(esim) {
  if (esim.status === "active") return { label: "Active", cls: "st-active", icon: <span className="pulse"></span> };
  if (esim.status === "finished") return { label: "Used up", cls: "st-ended", icon: <Ic.check style={{ width:13, height:13 }} /> };
  if (esim.status === "provisioning_failed") return { label: "Needs support", cls: "st-failed", icon: <Ic.x style={{ width:13, height:13 }} /> };
  if (esim.status === "provisioning_pending") return { label: "Provisioning", cls: "st-pending", icon: <span className="spinner" style={{ width:13, height:13 }}></span> };
  return { label: "Ready", cls: "st-ready", icon: <Ic.clock style={{ width:13, height:13 }} /> };
}

function hasInstallData(esim) {
  return !!(esim?.lpa || esim?.qrCodeUrl || esim?.qrDataUrl || esim?.checkoutMode === "test");
}

function appleEsimInstallUrl(esim) {
  const smdpAddress = String(esim?.smdpAddress || "").trim();
  const matchingId = String(esim?.matchingId || "").trim();
  const lpa = String(esim?.lpa || (smdpAddress && matchingId ? `LPA:1$${smdpAddress}$${matchingId}` : "")).trim();
  if (!/^LPA:/i.test(lpa)) return "";
  return `https://esimsetup.apple.com/esim_qrcode_provisioning?carddata=${encodeURIComponent(lpa)}`;
}

function readPendingEsimInstall() {
  try {
    return JSON.parse(sessionStorage.getItem(PENDING_ESIM_INSTALL_KEY) || "null");
  } catch (_) {
    return null;
  }
}

function writePendingEsimInstall(esim) {
  try {
    sessionStorage.setItem(PENDING_ESIM_INSTALL_KEY, JSON.stringify({
      uid: esim.uid,
      country: esim.country,
      flag: esim.flag,
      startedAt: Date.now(),
    }));
  } catch (_) {}
}

function clearPendingEsimInstall() {
  try {
    sessionStorage.removeItem(PENDING_ESIM_INSTALL_KEY);
  } catch (_) {}
}

function currentDeviceActivationSupport() {
  if (typeof navigator === "undefined") {
    return {
      canActivate: false,
      label: "Open on eSIM device",
      detail: "Use the QR on the phone that will use this eSIM.",
    };
  }

  const ua = navigator.userAgent || "";
  const platform = navigator.platform || "";
  const touchMac = platform === "MacIntel" && navigator.maxTouchPoints > 1;
  const isiPhoneOrIPad = /iPhone|iPad|iPod/i.test(ua) || touchMac;
  const isAndroid = /Android/i.test(ua);

  if (isiPhoneOrIPad) {
    return {
      canActivate: true,
      label: "Can activate here",
      detail: "This device can install the eSIM.",
    };
  }
  if (isAndroid) {
    return {
      canActivate: false,
      label: "Use QR on phone",
      detail: "Android eSIM support varies. Scan the QR from the eSIM phone.",
    };
  }
  return {
    canActivate: false,
    label: "Cannot activate here",
    detail: "Open this page on the eSIM phone or scan the QR from it.",
  };
}

function QRDisplay({ esim }) {
  if (esim.qrCodeUrl || esim.qrDataUrl) {
    return (
      <img src={esim.qrCodeUrl || esim.qrDataUrl} alt={`${esim.country} eSIM QR`}
        style={{ width: 174, height: 174, objectFit: "contain", borderRadius: 16, background: "#fff", padding: 10 }} />
    );
  }
  if (esim.checkoutMode === "test") return <QRGlyph uid={esim.uid} />;
  return (
    <div style={{ width: 174, minHeight: 132, borderRadius: 16, background: "rgba(255,255,255,0.06)",
      border: "1px solid var(--line)", display: "grid", placeItems: "center", padding: 18, textAlign: "center",
      color: "var(--muted)", fontSize: 13, lineHeight: 1.45 }}>
      Manual install details will appear here when the provider returns the QR code.
    </div>
  );
}

function EsimCard({ e, onActivate, onShowQR, onRefreshUsage, onInstallStarted }) {
  const [photoLoaded, setPhotoLoaded] = useStateE(false);
  const [photoFailed, setPhotoFailed] = useStateE(false);

  const photos = window.MARKETPLACE_PHOTOS || {};
  const grads  = window.MARKETPLACE_REGION_GRAD || {};
  const photoId  = photos[e.country];
  const photoUrl = photoId
    ? `https://images.unsplash.com/photo-${photoId}?w=600&q=80&auto=format&fit=crop`
    : null;
  const grad = grads[e.region] || ["#54388c", "#7ad0ff"];

  const pct    = e.totalMB > 0 ? Math.min(100, Math.round((e.usedMB / e.totalMB) * 100)) : 0;
  const expiry = e.activatedAt ? new Date(e.activatedAt + e.days * 864e5) : null;
  const networkLabel = esimNetworkLabel(e);
  const isUnlimited = !!e.unlimited || /^unlimited$/i.test(String(e.data || ""));
  const [activating, setActivating] = useStateE(false);
  const [refreshing, setRefreshing] = useStateE(false);
  const status = esimStatusMeta(e);
  const readyToInstall = e.status === "ready" && hasInstallData(e);
  const directInstallUrl = appleEsimInstallUrl(e);
  const deviceSupport = currentDeviceActivationSupport();
  const canActivateHere = readyToInstall && deviceSupport.canActivate && !!directInstallUrl;
  const activateButtonLabel = !readyToInstall
    ? "Install details pending"
    : canActivateHere
      ? "Activate"
      : deviceSupport.label;
  const usageCheckedLabel = e.usageUpdatedAt
    ? `Checked ${new Date(e.usageUpdatedAt).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })}`
    : "";

  const handleActivate = async () => {
    if (canActivateHere && directInstallUrl) {
      onInstallStarted(e);
      window.location.href = directInstallUrl;
      return;
    }
    setActivating(true);
    try { await onActivate(e.uid); } finally { setActivating(false); }
  };

  const handleRefreshUsage = async () => {
    setRefreshing(true);
    try { await onRefreshUsage(e.uid); } finally { setRefreshing(false); }
  };

  return (
    <div className="esim">
      <div className="esim-chip"></div>

      <div className="plan-banner" style={{ height: 170 }}>
        <div className="destimg"
          style={(!photoUrl || photoFailed) ? { background: `linear-gradient(160deg,${grad[0]},${grad[1]})` } : null}>
          {photoUrl && !photoFailed && (
            <img
              className={"destimg-photo" + (photoLoaded ? " in" : "")}
              src={photoUrl}
              alt={e.country}
              loading="lazy"
              onLoad={() => setPhotoLoaded(true)}
              onError={() => setPhotoFailed(true)}
            />
          )}
          <div className="destimg-scrim"></div>
        </div>
        <div style={{ position:"absolute", top:14, left:14, zIndex:2 }}>
          <span className={"esim-status " + status.cls}>
            {status.icon} {status.label}
          </span>
        </div>
        <div style={{ position:"absolute", top:14, right:14, zIndex:2,
          background:"rgba(0,0,0,0.55)", backdropFilter:"blur(6px)",
          borderRadius:999, padding:"5px 11px", fontSize:12, fontWeight:700, color:"#fff",
          border:"1px solid rgba(255,255,255,0.15)" }}>
          {e.status === "finished"
            ? "Plan ended"
            : e.status === "active" && expiry
            ? (() => { const d = Math.max(0, Math.ceil((expiry - Date.now()) / 864e5)); return d === 0 ? "Expires today" : `Expires in ${d}d`; })()
            : `Valid for ${e.days} days`}
        </div>
        <div className="plan-banner-name">{e.country}</div>
        <div className="plan-banner-region">{e.data} · {e.days} days</div>
      </div>

      <div className="esim-body">
        {e.status === "active" ? (
          <div className="usage">
            <div className="usage-row">
              <span>{fmtData(e.usedMB)} used</span>
              <span>{isUnlimited ? "Unlimited" : `${fmtData(e.totalMB - e.usedMB)} left`}</span>
            </div>
            <div className="usage-bar"><div className="usage-fill" style={{ width: (isUnlimited ? 100 : pct) + "%" }}></div></div>
          </div>
        ) : e.status === "finished" ? (
          <div className="usage">
            <div className="usage-row">
              <span>{fmtData(e.usedMB || e.totalMB)} used</span>
              <span>{isUnlimited ? "Ended" : "0 MB left"}</span>
            </div>
            <div className="usage-bar"><div className="usage-fill usage-fill-ended" style={{ width: "100%" }}></div></div>
          </div>
        ) : e.status === "provisioning_pending" ? (
          <div className="usage">
            <div className="usage-row"><span>Payment received</span><span>Waiting for provider</span></div>
            <div className="usage-bar"><div className="usage-fill" style={{ width: "18%" }}></div></div>
          </div>
        ) : e.status === "provisioning_failed" ? (
          <div className="usage">
            <div className="usage-row"><span>Payment received</span><span>Provisioning failed</span></div>
            <div className="usage-bar"><div className="usage-fill" style={{ width: "100%", background: "#ff6b6b" }}></div></div>
          </div>
        ) : (
          <div className="usage">
            <div className="usage-row"><span>{isUnlimited ? "Unlimited data ready" : `Full ${e.data} ready`}</span><span>Not started</span></div>
            <div className="usage-bar"><div className="usage-fill" style={{ width: "0%" }}></div></div>
          </div>
        )}

        {e.status === "ready" && (
          <div className={"device-compat" + (canActivateHere ? " can" : " cannot")}>
            <span className="device-compat-icon">
              {canActivateHere ? <Ic.check/> : <Ic.x/>}
            </span>
            <span>
              <strong>{!readyToInstall ? "Install details pending" : canActivateHere ? "Ready on this device" : deviceSupport.label}</strong>
              <small>{!readyToInstall ? "The provider has not returned the eSIM QR yet." : canActivateHere ? "Tap Activate to open the phone's eSIM setup." : deviceSupport.detail}</small>
            </span>
          </div>
        )}
        {(e.status === "active" || e.status === "finished") && usageCheckedLabel && (
          <div style={{ marginTop: 10, color: "var(--muted)", fontSize: 12 }}>
            {usageCheckedLabel}
          </div>
        )}

        <div style={{ display: "flex", gap: 10, marginTop: 18 }}>
          {e.status === "active" || e.status === "finished" ? (
            <>
              <button className="btn btn-ghost btn-sm" style={{ flex: 1 }} onClick={() => onShowQR(e)}><Ic.qr/> View QR</button>
              <button className="btn btn-accent btn-sm" style={{ flex: 1 }}
                onClick={handleRefreshUsage} disabled={refreshing}>
                {refreshing ? <span className="spinner"></span> : <><Ic.signal/> Refresh usage</>}
              </button>
            </>
          ) : e.status === "provisioning_pending" || e.status === "provisioning_failed" ? (
            <>
              <button className="btn btn-ghost btn-sm" onClick={() => onShowQR(e)}><Ic.qr/> Details</button>
              <button className="btn btn-accent btn-sm" style={{ flex: 1 }}
                onClick={handleRefreshUsage} disabled={refreshing || e.status === "provisioning_failed"}>
                {refreshing ? <span className="spinner"></span> : (e.status === "provisioning_failed" ? "Support needed" : <><Ic.signal/> Refresh status</>)}
              </button>
            </>
          ) : (
            <>
              <button className="btn btn-ghost btn-sm" onClick={() => onShowQR(e)}><Ic.qr/> QR</button>
              <button className="btn btn-accent btn-sm" style={{ flex: 1 }}
                onClick={handleActivate} disabled={activating || !canActivateHere}>
                {activating ? <span className="spinner"></span> : <><Ic.bolt/> {activateButtonLabel}</>}
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function MyEsims({ user, esims, onActivate, onRefreshUsage, go, onLogin, toast }) {
  const [qr, setQr] = useStateE(null);
  const [pendingInstall, setPendingInstall] = useStateE(() => readPendingEsimInstall());
  const [autoRefreshing, setAutoRefreshing] = useStateE(false);
  const autoRefreshKey = useRefE("");

  const pendingEsim = pendingInstall?.uid
    ? esims.find(e => e.uid === pendingInstall.uid)
    : null;

  useEffectE(() => {
    if (pendingInstall?.uid && ["active", "finished"].includes(pendingEsim?.status)) {
      clearPendingEsimInstall();
      setPendingInstall(null);
    }
  }, [pendingInstall?.uid, pendingEsim?.status]);

  const handleInstallStarted = (esim) => {
    writePendingEsimInstall(esim);
    setPendingInstall(readPendingEsimInstall());
  };

  useEffectE(() => {
    if (!user || !esims.length) return;
    const refreshable = esims
      .filter(esim => esim?.uid && esim.status !== "provisioning_failed")
      .map(esim => esim.uid);
    if (!refreshable.length) return;

    const key = `${user.id || user.email || "user"}:${refreshable.join(",")}`;
    if (autoRefreshKey.current === key) return;
    autoRefreshKey.current = key;

    let stopped = false;
    const refreshAll = async () => {
      setAutoRefreshing(true);
      for (const uid of refreshable) {
        if (stopped) break;
        try {
          await Store.refreshEsimUsage(uid);
        } catch (_) {}
      }
      if (!stopped) setAutoRefreshing(false);
    };
    refreshAll();

    return () => {
      stopped = true;
    };
  }, [user?.id, user?.email, esims.map(esim => esim.uid).join(",")]);

  useEffectE(() => {
    if (!pendingInstall?.uid || !user) return;

    let stopped = false;
    let timer = null;
    const startedAt = Number(pendingInstall.startedAt || Date.now());

    const check = async () => {
      if (stopped || document.hidden) return;
      try {
        const esim = await Store.refreshEsimUsage(pendingInstall.uid);
        if (stopped) return;
        if (["active", "finished"].includes(esim?.status)) {
          clearPendingEsimInstall();
          setPendingInstall(null);
          toast?.(esim.status === "finished" ? `${esim.flag} ${esim.country} eSIM plan has ended` : `${esim.flag} ${esim.country} eSIM is active`);
          stopped = true;
          return;
        }
      } catch (_) {}
      if (!stopped && Date.now() - startedAt < 10 * 60 * 1000) {
        timer = setTimeout(check, 15000);
      }
    };

    const handleVisible = () => {
      if (!document.hidden) check();
    };

    check();
    window.addEventListener("focus", check);
    document.addEventListener("visibilitychange", handleVisible);
    return () => {
      stopped = true;
      if (timer) clearTimeout(timer);
      window.removeEventListener("focus", check);
      document.removeEventListener("visibilitychange", handleVisible);
    };
  }, [pendingInstall?.uid, user?.id]);

  if (!user) {
    return (
      <div className="container empty">
        <div className="empty-ic"><Ic.user/></div>
        <h2 style={{ fontFamily: "var(--font-d)", fontSize: 26, margin: "0 0 8px" }}>Sign in to see your eSIMs</h2>
        <p style={{ color: "var(--muted)", margin: "0 0 22px" }}>Your purchased plans and activation QR codes live here.</p>
        <button className="btn btn-accent" onClick={onLogin}><GoogleG/> Sign in with Google</button>
      </div>
    );
  }

  if (!esims.length) {
    return (
      <div className="container empty">
        <div className="empty-ic"><Ic.qr/></div>
        <h2 style={{ fontFamily: "var(--font-d)", fontSize: 26, margin: "0 0 8px" }}>No eSIMs yet</h2>
        <p style={{ color: "var(--muted)", margin: "0 0 22px" }}>Pick up a plan and it'll appear here, ready to activate when you land.</p>
        <button className="btn btn-accent" onClick={() => go("marketplace")}><Ic.globe/> Browse the marketplace</button>
      </div>
    );
  }

  const active = esims.filter(e => e.status === "active").length;
  return (
    <div className="container">
      <div className="mkt-head" style={{ paddingBottom: 0 }}>
        <span className="eyebrow"><span className="dot"></span> {esims.length} eSIM{esims.length > 1 ? "s" : ""} · {active} active</span>
        <h1 className="mkt-title">My eSIMs</h1>
        <p style={{ color: "var(--muted)", fontSize: 16, marginTop: 12 }}>
          {autoRefreshing ? "Refreshing latest usage..." : "Manage data, check usage and activate when you arrive."}
        </p>
      </div>

      <div className="esim-list" style={{ marginTop: 30 }}>
        {esims.map(e => (
          <EsimCard key={e.uid} e={e} onShowQR={setQr} onActivate={onActivate}
            onRefreshUsage={onRefreshUsage} onInstallStarted={handleInstallStarted} />
        ))}
      </div>

      {qr && (
        <div className="modal-scrim" onClick={() => setQr(null)}>
          <div className="modal" style={{ maxWidth: 360 }} onClick={e => e.stopPropagation()}>
            <div className="modal-top">
              <div className="modal-x" onClick={() => setQr(null)}><Ic.x/></div>
              <h2 style={{ marginTop: 8 }}>{qr.flag} {qr.country}</h2>
              <p>{qr.status === "provisioning_pending" ? "Provider provisioning is still pending" : "Scan in Settings -> Mobile -> Add eSIM"}</p>
            </div>
            <div className="modal-body" style={{ display: "grid", placeItems: "center", paddingTop: 8 }}>
              <QRDisplay esim={qr} />
              <div style={{ fontFamily: "var(--font-d)", letterSpacing: "0.08em", fontSize: 11,
                color: "var(--muted)", marginTop: 16, wordBreak: "break-all", textAlign: "center" }}>
                {qr.lpa || qr.providerMessage || "Install code is not available yet."}
              </div>
              {qr.iccid && (
                <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 10, wordBreak: "break-all", textAlign: "center" }}>
                  ICCID {qr.iccid}
                </div>
              )}
              <p className="fineprint" style={{ marginTop: 14 }}>
                Each QR can be installed once. Keep it safe until you've added the eSIM to your device.
              </p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { MyEsims });
