/* eslint-disable */
/* =============================================================
   SettingsPage — account, preferences, notifications, privacy
   Browser build: classic <script type="text/babel">; window.SettingsPage
   ============================================================= */
(function () {
  const { useState } = React;

  function Toggle({ on, onChange }) {
    return (
      <button type="button" className={`tg ${on ? "on" : ""}`} onClick={() => onChange(!on)} aria-pressed={on}>
        <span className="tg-knob" />
      </button>
    );
  }

  function Segmented({ options, value, onChange }) {
    return (
      <div className="seg">
        {options.map((o, i) => (
          <button key={i} type="button" className={`seg-opt ${value === i ? "active" : ""}`} onClick={() => onChange(i)}>{o}</button>
        ))}
      </div>
    );
  }

  function Group({ title, children }) {
    return (
      <section className="set-group">
        <h2 className="set-group-title">{title}</h2>
        <div className="set-card">{children}</div>
      </section>
    );
  }

  function Row({ label, sub, children, danger }) {
    return (
      <div className={`set-row ${danger ? "is-danger" : ""}`}>
        <div className="set-row-text">
          <strong>{label}</strong>
          {sub && <span>{sub}</span>}
        </div>
        <div className="set-row-ctrl">{children}</div>
      </div>
    );
  }

  // ── Background mode picker (live preview via BgControl) ──
  function BgModePicker({ lang }) {
    const ar = lang === "ar";
    const [mode, setMode] = useState((window.BgControl && window.BgControl.get()) || "night");
    const MODES = [
      { id: "night",  ar: "ليل",   en: "Night",  icon: "moon",     hint: ar ? "السماء الكونية الداكنة" : "Deep cosmic night" },
      { id: "dawn",   ar: "صبح",   en: "Dawn",   icon: "sun",      hint: ar ? "فجر فاتح، الكروت تفضل داكنة" : "Pale sunrise" },
      { id: "auto",   ar: "تلقائي", en: "Auto",  icon: "compass",  hint: ar ? "حسب وقت وموقع جهازك" : "By device time + location" },
      { id: "static", ar: "ثابت",  en: "Static", icon: "star",     hint: ar ? "سماء ثابتة بحركة خفيفة" : "Stilled sky" },
      { id: "off",    ar: "مقفولة", en: "Off",   icon: "eye",      hint: ar ? "إيقاف الخلفية تمامًا" : "Background off" },
    ];
    const pick = (id) => { setMode(id); window.BgControl && window.BgControl.set(id); };
    const cur = MODES.find((m) => m.id === mode) || MODES[0];
    return (
      <div className="bgmode">
        <div className="bgmode-grid">
          {MODES.map((m) => {
            const I = Icon[m.icon] || Icon.moon;
            return (
              <button key={m.id} type="button" className={`bgmode-opt ${mode === m.id ? "active" : ""}`} onClick={() => pick(m.id)}>
                <span className="bgmode-ic"><I size={17} /></span>
                <span className="bgmode-label">{ar ? m.ar : m.en}</span>
              </button>
            );
          })}
        </div>
        <p className="bgmode-hint">{cur.hint}</p>
      </div>
    );
  }

  // ── Tone picker (site-wide content register) ──
  function TonePicker({ lang }) {
    const ar = lang === "ar";
    const [tone, setTone] = useState(window.SpadeTone ? SpadeTone.get() : "simple");
    const opts = (window.SpadeTone ? SpadeTone.tonesFor(lang) : ["simple"]);
    return (
      <div className="seg seg-wrap">
        {opts.map((t) => (
          <button key={t} type="button" className={`seg-opt ${tone === t ? "active" : ""}`}
            onClick={() => { setTone(t); window.SpadeTone && SpadeTone.set(t); }}>
            {window.SpadeTone ? SpadeTone.label(t, lang) : t}
          </button>
        ))}
      </div>
    );
  }

  window.SettingsPage = function SettingsPage({ lang, onRoute, onLangToggle }) {
    const S = I18N[lang].settings;
    const ar = lang === "ar";
    const user = window.CHART_SUMMARY || {};
    const remote = window.ChartStore?.remote;
    const account = remote ? ChartStore.currentUser() : null;
    const accountName = remote ? [account?.firstName, account?.lastName].filter(Boolean).join(" ") || "—" : (ar ? user.name_ar : user.name_en);
    const accountEmail = remote ? account?.email || "—" : "spade@spadeslife.com";
    const [pref, setPref] = useState({ motion: false, tabular: true, email: true, push: true, labsNews: false, hide: false });
    const set = (k) => (v) => setPref((p) => ({ ...p, [k]: v }));
    const tt = (a2, e2) => (ar ? a2 : e2);
    const toast = (type, title, msg) => window.HDToast && HDToast.show({ type, title, msg });
    const onChangeEmail = () => toast("info", tt("تأكيد البريد", "Verify email"), tt("أرسلنا رابط تأكيد إلى بريدك لتعديله.", "We sent a verification link to update your email."));
    const onExportData = () => toast("info", tt("جارٍ تجهيز بياناتك", "Preparing your data"), tt("سنرسل لك ملفًا بكل بياناتك قريبًا.", "We'll email you an archive of your data shortly."));
    const onDeleteAccount = () => window.HDConfirm && HDConfirm.open({
      title: tt("حذف الحساب نهائيًا؟", "Delete account permanently?"),
      msg: tt("سيُحذف حسابك وكل خرائطك ولا يمكن التراجع عن هذا الإجراء.", "Your account and all your charts will be erased. This cannot be undone."),
      confirmText: tt("حذف الحساب", "Delete account"), cancelText: tt("إلغاء", "Cancel"), danger: true,
      onConfirm: () => { toast("success", tt("تم حذف الحساب", "Account deleted"), ""); onRoute && onRoute("auth"); },
    });

    return (
      <div className="page page-settings">
        <PageHeader lang={lang} title={S.title} sub={S.sub} />

        <div className="settings-grid">
          <div className="settings-col">
            <Group title={S.groups.account}>
              <div className="set-account">
                <div className="set-avatar">{accountName?.trim()?.[0] || "—"}</div>
                <div className="set-account-text">
                  <strong>{accountName}</strong>
                  <span dir="ltr">{accountEmail}</span>
                </div>
                {!remote && <button className="btn-ghost set-mini" onClick={onChangeEmail}>{S.change}</button>}
              </div>
              <Row label={S.account_name}>
                <input className="set-input" aria-label={S.account_name} defaultValue={accountName} readOnly={remote} />
              </Row>
              <Row label={S.account_email}>
                <input className="set-input" aria-label={S.account_email} defaultValue={accountEmail} readOnly={remote} />
              </Row>
              {remote && !ChartStore.isAdmin() && <Row label={tt("بيانات الميلاد المؤكدة", "Confirmed birth details")} sub={tt("لو في خطأ، إدارة البيتا تقدر تصحّحه.", "The beta team can correct these details.")}>
                <span>{[user.birth_date, user.birth_time, ar ? user.birth_place_ar : user.birth_place_en].filter(Boolean).join(" · ") || "—"}</span>
              </Row>}
            </Group>

            <Group title={S.groups.prefs}>
              <Row label={S.lang}>
                <button className="btn-ghost set-mini" onClick={onLangToggle}>
                  <Icon.globe size={14} /> {ar ? "English" : "العربية"}
                </button>
              </Row>
              <Row label={ar ? "الخلفية" : "Background"} sub={ar ? "تحكّم في السماء الكونية خلف الموقع" : "Control the cosmic sky behind the app"}>
                <span></span>
              </Row>
              <div className="set-row set-row-full"><BgModePicker lang={lang} /></div>
              {!remote && <><Row label={ar ? "نبرة الشرح" : "Explanation tone"} sub={ar ? "صيغة كل الشروحات في الموقع — تتغيّر فورًا" : "The voice of every explanation on the site — changes instantly"}>
                <span></span>
              </Row>
              <div className="set-row set-row-full"><TonePicker lang={lang} /></div></>}
              {!remote && <>
                <Row label={S.motion} sub={S.motion_sub}><Toggle on={pref.motion} onChange={set("motion")} /></Row>
                <Row label={S.tabular}><Toggle on={pref.tabular} onChange={set("tabular")} /></Row>
              </>}
              {/* الافتتاحية تُعرَض مرّة واحدة؛ بلا هذا الزرّ لا سبيل
                  لتجربتها ثانيةً إلا بمسح تخزين المتصفّح كلّه. */}
              <Row label={(I18N[lang].birth_sky || {}).replay}>
                <button
                  className="btn-outline"
                  onClick={() => {
                    if (!window.BirthSkyIntro) return;
                    window.dispatchEvent(new Event("hd-birthsky-replay"));
                  }}
                >
                  {ar ? "عرض" : "Play"}
                </button>
              </Row>
            </Group>
          </div>

          {!remote && <div className="settings-col">
            <Group title={S.groups.notif}>
              <Row label={S.notif_email} sub={S.notif_email_sub}><Toggle on={pref.email} onChange={set("email")} /></Row>
              <Row label={S.notif_push} sub={S.notif_push_sub}><Toggle on={pref.push} onChange={set("push")} /></Row>
              <Row label={S.notif_labs} sub={S.notif_labs_sub}><Toggle on={pref.labsNews} onChange={set("labsNews")} /></Row>
            </Group>

            <Group title={S.groups.privacy}>
              <Row label={S.privacy_profile}><Toggle on={pref.hide} onChange={set("hide")} /></Row>
              <Row label={S.privacy_data}>
                <button className="btn-ghost set-mini" onClick={onExportData}><Icon.download size={14} /> {S.privacy_data_cta}</button>
              </Row>
            </Group>

            {/* The plan card's upgrade and billing buttons went with the
                paid tier. The admin link stays — it is gated by
                SpadeAccess and has nothing to do with payment. */}
            {window.SpadeAccess && SpadeAccess.isAdmin() && (
              <div className="plan-card">
                <button className="btn-ghost set-mini plan-manage" onClick={() => onRoute && onRoute("admin")}><Icon.settings size={14} /> {ar ? "لوحة الإدارة (داخلي)" : "Admin console (internal)"}</button>
              </div>
            )}
          </div>}
        </div>

        <section className="danger-zone">
          <h2 className="set-group-title danger">{S.danger}</h2>
          <div className="set-card">
            <Row label={S.signout}>
              <button className="btn-ghost set-mini" onClick={async () => {
                await window.ChartStore?.logout();
                onRoute?.("auth");
              }}><Icon.logout size={14} /> {S.signout}</button>
            </Row>
            {!window.ChartStore?.remote && <Row label={S.delete} sub={S.delete_sub} danger>
              <button className="btn-danger set-mini" onClick={onDeleteAccount}>{S.delete}</button>
            </Row>}
          </div>
        </section>
      </div>
    );
  };
})();
