// session.jsx — Level 1: guest session + roles, hero question, trust band,
// and the soft signup nudge. The authentication UI lives in auth.jsx.
// Browser state is device-local preview state and never proves authentication.

// Tri-lingual accessor (ar falls back to en)
const L = (lang, o) => o && (o[lang] || o.en) || "";

// ---------------------------------------------------------------------------
// Strings (kept local to this section so we don't bloat data.jsx)
// ---------------------------------------------------------------------------
const S = {
  heroQ: { fa: "چه کمک حقوقی می‌خواهید؟", ar: "ما هي المساعدة القانونية التي تحتاجها؟", en: "What legal help do you need?" },
  heroSub: { fa: "آرام بپرسید؛ شهداد راهنمایی‌تان می‌کند — بدون نیاز به ثبت‌نام.", ar: "اسأل بهدوء؛ شهداد يرشدك — دون الحاجة للتسجيل.", en: "Ask freely. Shahdad guides you — no sign-up required." },
  heroPh: { fa: "سوال حقوقی‌تان را بنویسید… مثلاً «مهریه‌ام را چطور وصول کنم؟»", ar: "اكتب سؤالك القانوني… مثلاً «كيف أحصل على مهري؟»", en: "Type your legal question… e.g. \u201CHow do I claim my dowry?\u201D" },
  heroBtn: { fa: "بپرس", ar: "اسأل", en: "Ask" },
  trust: [
  { fa: "رمزنگاری سرتاسری", ar: "تشفير من طرف إلى طرف", en: "End-to-end encrypted" },
  { fa: "بدون نیاز به ثبت‌نام", ar: "بدون تسجيل", en: "No sign-up required" },
  { fa: "مطابق قوانین ایران", ar: "متوافق مع القانون الإيراني", en: "Compliant with Iranian law" }],

  nudgeT: { fa: "برای ذخیرهٔ کارها و پرونده‌هایتان، یک حساب رایگان بسازید.", ar: "أنشئ حساباً مجانياً لحفظ أعمالك وقضاياك.", en: "Create a free account to save your work and cases." },
  nudgeBtn: { fa: "ثبت‌نام رایگان", ar: "تسجيل مجاني", en: "Sign up free" },
  ecoEntry: { fa: "کاوش کامل اکوسیستم", ar: "استكشف النظام الكامل", en: "Explore the full ecosystem" }
};

// ---------------------------------------------------------------------------
// Session context — guest-first, role-aware, persisted to localStorage.
// Role structure ready from day one: guest | user | lawyer | org | admin.
// ---------------------------------------------------------------------------
const SessionCtx = React.createContext(null);
const useSession = () => React.useContext(SessionCtx);

const SESSION_KEY = "shahdad_session_v1";
const newGuestId = () => "guest_" + Math.random().toString(36).slice(2, 8) + Date.now().toString(36).slice(-4);
const freshGuestSession = (raw = {}) => ({
  guestId: typeof raw.guestId === "string" && raw.guestId.startsWith("guest_")
    ? raw.guestId
    : newGuestId(),
  authState: "guest",
  role: "guest",
  displayName: null,
  subscription: null,
  saved: Array.isArray(raw.saved) ? raw.saved.filter((item) => typeof item === "string").slice(0, 100) : []
});

// Persisted browser data is allow-listed to guest-only preferences. A forged
// authState, role, displayName or subscription can never hydrate as signed in.
const getLocalPlanPreview = () => {
  if (typeof window === "undefined") return null;
  const isLoopback = ["127.0.0.1", "localhost", "::1"].includes(window.location.hostname);
  const requestedPlan = new URLSearchParams(window.location.search).get("previewPlan");
  if (!isLoopback || requestedPlan !== "earth") return null;
  return {
    guestId: "local_earth_preview",
    authState: "authenticated",
    role: "user",
    displayName: "کاربر آزمایشی",
    subscription: {
      planId: "earth",
      planName: { fa: "زمین", en: "Earth" },
      status: "active",
      scope: "account",
      source: "local-preview",
      startedAt: null,
      expiresAt: null
    },
    saved: [],
    localPreview: true
  };
};

const normalizeSessionState = (raw) => getLocalPlanPreview() || freshGuestSession(raw || {});

const SessionProvider = ({ children }) => {
  const [state, setState] = React.useState(() => {
    let s = null;
    try {s = JSON.parse(localStorage.getItem(SESSION_KEY));} catch (e) {}
    if (!s || !s.guestId) {
      // Device-local guest identifier only. Never replace this value with an
      // authentication token; real sessions belong in secure server cookies.
      s = freshGuestSession();
    }
    return normalizeSessionState(s);
  });

  React.useEffect(() => {
    if (state.localPreview) return;
    try {localStorage.setItem(SESSION_KEY, JSON.stringify(state));} catch (e) {}
  }, [state]);

  const api = React.useMemo(() => ({
    ...state,
    isGuest: state.authState !== "authenticated",
    isAuthenticated: state.authState === "authenticated",
    // Real sign-in will be hydrated from GET /api/session after an HttpOnly
    // cookie is verified. No client-side login mutator exists in this release.
    logout: () => setState(freshGuestSession()),
    // Profile role is a local draft only and must never be used for authorization.
    setRole: (role) => setState((s) => ({ ...s, role })),
    saveItem: (id) => setState((s) => s.saved.includes(id) ? s : { ...s, saved: [...s.saved, id] })
  }), [state]);

  return <SessionCtx.Provider value={api}>{children}</SessionCtx.Provider>;
};

// ---------------------------------------------------------------------------
// Hero — calm central question above the search, routes to the AI assistant.
// ---------------------------------------------------------------------------
const Hero = ({ lang, onOpen }) => {
  const [q, setQ] = React.useState("");
  const ask = () => {
    if (!q.trim()) return;
    window.__pendingAsk = q.trim(); // consumed by AIChatView on open
    AudioCtl.open();
    onOpen("aiChat");
    setQ("");
  };
  return (
    <div className="hero" data-screen-label="home-hero">
      <div className="hero-inner">
        <h1 className="hero-q">{L(lang, S.heroQ)}</h1>
        <p className="hero-sub">{L(lang, S.heroSub)}</p>
        <div className="hero-ask">
          <Ic.bot size={18} className="hero-ask-ico" />
          <input
            value={q}
            onChange={(e) => setQ(e.target.value)}
            onKeyDown={(e) => {if (e.key === "Enter") ask();}}
            placeholder={L(lang, S.heroPh)} />
          <button className="hero-ask-btn" onClick={ask}>
            <span>{L(lang, S.heroBtn)}</span><Ic.send size={15} />
          </button>
        </div>
        <div className="trust-band">
          {S.trust.map((it, i) =>
          <span key={i} className="trust-item"><Ic.shieldCheck size={12} /> {L(lang, it)}</span>
          )}
        </div>
        <button className="eco-entry" onClick={() => {AudioCtl.open();onOpen("ecosystem");}}>
          <Ic.chip size={14} />
          <span>{L(lang, S.ecoEntry)}</span>
          <span className="eco-entry-meta">{lang === "en" ? "5 layers · 53 modules" : lang === "ar" ? "٥ طبقات · ٥٣ وحدة" : "۵ لایه · ۵۳ ماژول"}</span>
          <Ic.chevL size={13} />
        </button>
      </div>
    </div>);

};

// ---------------------------------------------------------------------------
// Soft, dismissible signup nudge (frequency-capped by the host app).
// ---------------------------------------------------------------------------
const GuestNudge = ({ lang, onSignup, onClose }) =>
<div className="guest-nudge" role="status">
    <div className="gn-ico"><Ic.user size={16} /></div>
    <div className="gn-body"><div className="gn-title">{L(lang, S.nudgeT)}</div></div>
    <button className="gn-cta" onClick={onSignup}>{L(lang, S.nudgeBtn)}</button>
    <button
      className="gn-x"
      onClick={onClose}
      aria-label={lang === "fa" ? "بستن پیشنهاد ثبت‌نام" : lang === "ar" ? "إغلاق اقتراح التسجيل" : "Dismiss sign-up suggestion"}
    ><Ic.close size={14} /></button>
  </div>;

Object.assign(window, { SessionProvider, useSession, Hero, GuestNudge });
