// Install prompt modal (iOS) + Notifications screen + Settings screen

function InstallPrompt({ onDone, onLater }) {
  return (
    <div className="modal-overlay">
      <div className="modal-card">
        <div className="modal-icon">f</div>
        <div className="modal-title">ADD TO HOME SCREEN</div>
        <div className="modal-body">
          To get the morning bell, Future Self needs to live on your home screen.
        </div>
        <div className="install-steps">
          <div className="install-step">
            <span className="num">1</span>
            <span>Tap the Share button <span className="share-ic"><IconShare size={16}/></span> in Safari</span>
          </div>
          <div className="install-step">
            <span className="num">2</span>
            <span>Scroll to &ldquo;Add to Home Screen&rdquo;</span>
          </div>
          <div className="install-step">
            <span className="num">3</span>
            <span>Tap Add</span>
          </div>
        </div>
        <div className="modal-actions">
          <button className="submit-btn" onClick={onDone}>I did it</button>
          <button className="skip-btn" onClick={onLater}>Remind me later</button>
        </div>
      </div>
    </div>
  );
}

function NotificationsScreen({ onEnable, onLater }) {
  return (
    <div className="screen no-tabs">
      <div className="notif-screen">
        <div className="bell-icon"><IconBell size={56}/></div>
        <div className="notif-title">TURN ON THE<br/>MORNING BELL.</div>
        <div className="notif-body">
          <em>8 AM every day.</em> One notification. Tap to listen.<br/>That&rsquo;s it. No noise.
        </div>
        <div className="notif-actions">
          <button className="submit-btn" onClick={onEnable}>Enable</button>
          <button className="skip-btn" onClick={onLater}>Not yet</button>
        </div>
      </div>
    </div>
  );
}

function SettingsRow({ k, v, onSave, kind = "text", options }) {
  const [editing, setEditing] = React.useState(false);
  const [draft, setDraft] = React.useState(v || "");
  React.useEffect(() => { setDraft(v || ""); }, [v]);

  const commit = async () => {
    if (draft === v) { setEditing(false); return; }
    try { await onSave(draft); } catch (e) { console.warn("save failed:", e); }
    setEditing(false);
  };

  if (editing && kind === "text") {
    return (
      <div className="settings-row">
        <span className="k">{k}</span>
        <input
          className="text-input"
          style={{ padding: "8px 12px", fontSize: 14, maxWidth: 180 }}
          value={draft}
          autoFocus
          onChange={e => setDraft(e.target.value)}
          onBlur={commit}
          onKeyDown={e => { if (e.key === "Enter") commit(); if (e.key === "Escape") { setDraft(v || ""); setEditing(false); } }}
        />
      </div>
    );
  }
  if (editing && kind === "select") {
    return (
      <div className="settings-row">
        <span className="k">{k}</span>
        <select
          className="text-input"
          style={{ padding: "8px 12px", fontSize: 14 }}
          value={draft}
          autoFocus
          onChange={e => { setDraft(e.target.value); setTimeout(() => { (async () => { try { await onSave(e.target.value); } catch (err) { console.warn(err); } setEditing(false); })(); }, 0); }}
          onBlur={commit}
        >
          {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
        </select>
      </div>
    );
  }

  const displayV = kind === "select" && options
    ? (options.find(o => o.value === v)?.label || v || "—")
    : (v || "—");

  return (
    <div className="settings-row" onClick={() => setEditing(true)} style={{ cursor: "pointer" }}>
      <span className="k">{k}</span>
      <span className="v">{displayV} <span className="edit">{kind === "select" ? "▾" : "✎"}</span></span>
    </div>
  );
}

function SettingsScreen({ onBack, onRerecord, hasCloned, setHasCloned, notifOn, setNotifOn, user }) {
  const [voice, setVoice] = React.useState(hasCloned ? "mine" : "charlie");
  const [profile, setProfile] = React.useState(user || {});
  React.useEffect(() => { setProfile(user || {}); }, [user]);

  // Credential setter — Kaku's migration path. Only rendered when the
  // current user doesn't yet have a password (has_credentials: false).
  const [showCreds, setShowCreds] = React.useState(false);
  const [credU, setCredU]         = React.useState("");
  const [credP, setCredP]         = React.useState("");
  const [credBusy, setCredBusy]   = React.useState(false);
  const [credErr, setCredErr]     = React.useState("");

  const submitCreds = async () => {
    if (credBusy) return;
    if (credU.trim().length < 3 || credP.length < 8) {
      setCredErr("Username needs 3+ chars, password 8+.");
      return;
    }
    setCredBusy(true); setCredErr("");
    try {
      await api.setCredentials({ username: credU.trim(), password: credP });
      location.reload();
    } catch (e) {
      setCredErr(e?.status === 409 ? "Username taken." : "Couldn't save. Try again.");
    } finally {
      setCredBusy(false);
    }
  };

  const logout = async () => {
    try { await api.logout(); } catch {}
    location.reload();
  };

  const save = async (field, value) => {
    setProfile(p => ({ ...p, [field]: value }));
    await api.updateProfile({ [field]: value });
  };

  return (
    <div className="screen">
      <div className="settings">
        <div className="settings-header">
          <button className="back" onClick={onBack} aria-label="Back"><IconBack/></button>
          <div className="title">SETTINGS</div>
        </div>

        <div className="settings-group">
          <h4>Your voice</h4>
          <div className="voice-pick">
            <div className={`voice-option ${voice === "mine" ? "on" : ""}`} onClick={() => hasCloned && setVoice("mine")}>
              <span className="radio"/>
              <span className="name">Your cloned voice</span>
              <span className="meta">{hasCloned ? "Ready" : "Not set"}</span>
            </div>
            <div className={`voice-option ${voice === "charlie" ? "on" : ""}`} onClick={() => setVoice("charlie")}>
              <span className="radio"/>
              <span className="name">Charlie</span>
              <span className="meta">Preset</span>
            </div>
          </div>
          <button className="rerecord-btn" onClick={onRerecord}>
            {hasCloned ? "Re-record my voice" : "Record my voice"}
          </button>
        </div>

        <div className="section-divider"/>

        <div className="settings-group">
          <h4>Your profile</h4>
          <SettingsRow k="Name" v={profile.name} onSave={v => save("name", v)}/>
          <SettingsRow k="Situation" v={profile.situation} onSave={v => save("situation", v)}/>
          <SettingsRow k="Goals" v={profile.goals} onSave={v => save("goals", v)}/>
          <SettingsRow
            k="Language"
            v={profile.lang_pref || "hinglish"}
            kind="select"
            options={[
              { value: "english", label: "English" },
              { value: "hindi", label: "Hindi" },
              { value: "hinglish", label: "Hinglish" },
            ]}
            onSave={v => save("lang_pref", v)}
          />
        </div>

        <div className="section-divider"/>

        <div className="settings-group">
          <h4>Delivery</h4>
          <div className="settings-row">
            <span className="k">Notifications</span>
            <span
              className={`switch ${notifOn ? "on" : ""}`}
              role="switch"
              aria-checked={notifOn}
              onClick={() => setNotifOn(!notifOn)}
            />
          </div>
          <SettingsRow
            k="Morning time"
            v={String(profile.delivery_hour ?? 8)}
            kind="select"
            options={Array.from({ length: 12 }, (_, i) => ({ value: String(i + 5), label: `${i + 5}:00 AM` }))}
            onSave={v => save("delivery_hour", parseInt(v, 10))}
          />
          <SettingsRow k="City" v={profile.city || "Mumbai"} onSave={v => save("city", v)}/>
        </div>

        <div className="section-divider"/>

        <div className="settings-group">
          <h4>Account</h4>
          {profile.username && (
            <div className="settings-row">
              <span className="k">Username</span>
              <span className="v">{profile.username}</span>
            </div>
          )}

          {!profile.has_credentials && (
            showCreds ? (
              <div className="creds-form">
                <input
                  className="text-input"
                  value={credU}
                  onChange={e => setCredU(e.target.value)}
                  placeholder="username"
                  autoCapitalize="none"
                  autoCorrect="off"
                />
                <input
                  className="text-input"
                  type="password"
                  value={credP}
                  onChange={e => setCredP(e.target.value)}
                  placeholder="8+ char password"
                />
                {credErr && <div className="onboard-error" role="alert">{credErr}</div>}
                <button
                  className="onboard-next"
                  onClick={submitCreds}
                  disabled={credBusy}
                >{credBusy ? "…" : "Save"}</button>
              </div>
            ) : (
              <div className="settings-row" onClick={() => setShowCreds(true)} style={{ cursor: "pointer" }}>
                <span className="k">Set username &amp; password</span>
                <span className="v"><span className="edit">›</span></span>
              </div>
            )
          )}

          <div className="settings-row logout-row" onClick={logout} style={{ cursor: "pointer" }}>
            <span className="k">Log out</span>
            <span className="v"><span className="edit">›</span></span>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { InstallPrompt, NotificationsScreen, SettingsScreen });
