// ─────────────────────────────────────────────────────────
// ChefVerse · Profile page (chef-facing)
// Sections:
//  • Hero — avatar (with corner camera) + name + role pill + market
//  • Your numbers — 4 stat tiles
//  • Account details — editable: name, email, role, restaurant, years, channels; read-only: market
//  • Shipping address — editable address for reward shipping
//  • Password — change password CTA
//  • Danger zone — request account deletion, sign out
// (Preferences moved to Settings page.)
// ─────────────────────────────────────────────────────────

const PROFILE_I18N = {
  en: {
    title: "Your profile",
    sub: "How ChefVerse sees you, and what you can change.",
    edit: "Edit",
    editProfile: "Edit profile",
    save: "Save changes",
    cancel: "Cancel",
    yourStatsTitle: "Your numbers",
    yourStatsSub: "Quick view of what you've shipped so far.",
    statModulesDone: "Modules completed",
    statBriefsDone: "Briefs submitted",
    statRewards: "Reward points",
    statStreak: "Day streak",
    accountTitle: "Account details",
    accountSub: "These are tied to your work email. Need a different email? Ask your UFS rep.",
    fieldName: "Full name",
    fieldEmail: "Work email",
    fieldRole: "Role",
    fieldRestaurant: "Where you work",
    fieldYears: "Years in professional kitchens",
    fieldMarket: "Region",
    channelsTitle: "Channels",
    channelsSub: "Where you post — so we know how to size and frame your content.",
    chInstagram: "Instagram handle",
    chTiktok: "TikTok handle",
    chFacebook: "Facebook page",
    chYoutube: "YouTube channel",
    shippingTitle: "Shipping address",
    shippingSub: "Where we'll send physical rewards (merch, equipment).",
    shipLine1: "Street address",
    shipLine2: "Apt, suite, floor (optional)",
    shipCity: "City",
    shipPostal: "Postal code",
    shipRegion: "State / Region",
    shipCountry: "Country",
    pwTitle: "Password",
    pwSub: "Change your password whenever it feels stale.",
    pwChange: "Change password",
    dangerTitle: "Account actions",
    dangerSub: "Sign out or close your ChefVerse account.",
    dangerDelete: "Request account deletion",
    dangerSignOut: "Sign out",
    saved: "Profile updated",
    avatarHint: "JPG or PNG · square works best",
    uploadAvatar: "Change photo",
    // Roles for the select (matches onboarding role_keys)
    role_chef: "Head chef",
    role_sous: "Sous chef",
    role_owner: "Owner-operator",
    role_pastry: "Pastry chef",
    role_consult: "Consultant chef",
  },
  de: {
    title: "Dein Profil",
    sub: "Wie ChefVerse dich sieht, und was du ändern kannst.",
    edit: "Bearbeiten",
    editProfile: "Profil bearbeiten",
    save: "Änderungen speichern",
    cancel: "Abbrechen",
    yourStatsTitle: "Deine Zahlen",
    yourStatsSub: "Schnelle Übersicht, was du geliefert hast.",
    statModulesDone: "Module abgeschlossen",
    statBriefsDone: "Briefings eingereicht",
    statRewards: "Belohnungspunkte",
    statStreak: "Tage-Streak",
    accountTitle: "Kontodetails",
    accountSub: "Diese sind an deine geschäftliche E-Mail gebunden. Andere E-Mail? Frag deinen UFS-Kontakt.",
    fieldName: "Vollständiger Name",
    fieldEmail: "Geschäftliche E-Mail",
    fieldRole: "Rolle",
    fieldRestaurant: "Wo du arbeitest",
    fieldYears: "Jahre in der Profi-Küche",
    fieldMarket: "Region",
    channelsTitle: "Kanäle",
    channelsSub: "Wo du postest — damit wir Inhalte passend skalieren.",
    chInstagram: "Instagram-Handle",
    chTiktok: "TikTok-Handle",
    chFacebook: "Facebook-Seite",
    chYoutube: "YouTube-Kanal",
    shippingTitle: "Versandadresse",
    shippingSub: "Wohin wir physische Belohnungen schicken (Merch, Equipment).",
    shipLine1: "Straße und Hausnummer",
    shipLine2: "Wohnung, Etage (optional)",
    shipCity: "Stadt",
    shipPostal: "Postleitzahl",
    shipRegion: "Bundesland / Region",
    shipCountry: "Land",
    pwTitle: "Passwort",
    pwSub: "Ändere dein Passwort wann immer es sich abgenutzt anfühlt.",
    pwChange: "Passwort ändern",
    dangerTitle: "Konto-Aktionen",
    dangerSub: "Abmelden oder ChefVerse-Konto schließen.",
    dangerDelete: "Kontolöschung anfordern",
    dangerSignOut: "Abmelden",
    saved: "Profil aktualisiert",
    avatarHint: "JPG oder PNG · quadratisch passt am besten",
    uploadAvatar: "Foto ändern",
    role_chef: "Küchenchef",
    role_sous: "Sous chef",
    role_owner: "Inhaber-Betreiber",
    role_pastry: "Patissier",
    role_consult: "Beraterchef",
  },
  id: {
    title: "Profilmu",
    sub: "Bagaimana ChefVerse melihatmu, dan apa yang bisa kamu ubah.",
    edit: "Edit",
    editProfile: "Edit profil",
    save: "Simpan",
    cancel: "Batal",
    yourStatsTitle: "Angka-angkamu",
    yourStatsSub: "Ringkasan apa yang sudah kamu kirim.",
    statModulesDone: "Modul selesai",
    statBriefsDone: "Brief dikirim",
    statRewards: "Poin reward",
    statStreak: "Hari berturut",
    accountTitle: "Detail akun",
    accountSub: "Ini terikat ke email kerjamu. Perlu email lain? Tanya kontak UFS-mu.",
    fieldName: "Nama lengkap",
    fieldEmail: "Email kerja",
    fieldRole: "Peran",
    fieldRestaurant: "Tempat kamu bekerja",
    fieldYears: "Tahun di dapur profesional",
    fieldMarket: "Wilayah",
    channelsTitle: "Channel",
    channelsSub: "Di mana kamu posting — supaya kami tahu cara framing kontennya.",
    chInstagram: "Handle Instagram",
    chTiktok: "Handle TikTok",
    chFacebook: "Halaman Facebook",
    chYoutube: "Channel YouTube",
    shippingTitle: "Alamat pengiriman",
    shippingSub: "Tempat kami kirim reward fisik (merch, peralatan).",
    shipLine1: "Alamat jalan",
    shipLine2: "Unit, lantai (opsional)",
    shipCity: "Kota",
    shipPostal: "Kode pos",
    shipRegion: "Provinsi / Region",
    shipCountry: "Negara",
    pwTitle: "Kata sandi",
    pwSub: "Ganti kata sandi kapan pun terasa basi.",
    pwChange: "Ubah kata sandi",
    dangerTitle: "Tindakan akun",
    dangerSub: "Keluar atau tutup akun ChefVerse kamu.",
    dangerDelete: "Minta hapus akun",
    dangerSignOut: "Keluar",
    saved: "Profil diperbarui",
    avatarHint: "JPG atau PNG · persegi paling pas",
    uploadAvatar: "Ganti foto",
    role_chef: "Head chef",
    role_sous: "Sous chef",
    role_owner: "Pemilik-operator",
    role_pastry: "Pastry chef",
    role_consult: "Konsultan chef",
  },
};

// Market display based on locale (since profile.location was per-locale string)
const MARKETS = {
  en: { code: "us", label: "United States", flag: "🇺🇸" },
  de: { code: "de", label: "Deutschland", flag: "🇩🇪" },
  id: { code: "id", label: "Indonesia", flag: "🇮🇩" },
};

function ProfilePage({ locale, profile, onLogout, onChangePassword }) {
  const tl = PROFILE_I18N[locale] || PROFILE_I18N.en;
  // Per-section edit state: null when idle, or one of "account" | "channels" | "shipping"
  const [editingSection, setEditingSection] = React.useState(null);
  const [savedToast, setSavedToast] = React.useState(false);
  const editingAccount = editingSection === "account";
  const editingChannels = editingSection === "channels";
  const editingShipping = editingSection === "shipping";
  
  // Seed values
  const initialName = profile.name || "Chef";
  const initialEmail = profile.email || (initialName.toLowerCase().replace(/\s+/g, ".") + "@yourrestaurant.com");
  const initialRestaurant = profile.restaurant || (locale === "de" ? "Kantine Berlin Mitte" : locale === "id" ? "Warung Bali Sunset" : "Lower East Side Bistro");
  const initialYears = profile.years || "4";
  const initialChannels = profile.channels || { instagram: "", tiktok: "", facebook: "", youtube: "" };
  const initialShipping = profile.shipping || { line1: "", line2: "", city: "", postal: "", region: "", country: "" };
  
  // Editable state (cloned)
  const [name, setName] = React.useState(initialName);
  const [email, setEmail] = React.useState(initialEmail);
  const [roleKey, setRoleKey] = React.useState(profile.role_key || "role_sous");
  const [restaurant, setRestaurant] = React.useState(initialRestaurant);
  const [years, setYears] = React.useState(initialYears);
  const [channels, setChannels] = React.useState(initialChannels);
  const [shipping, setShipping] = React.useState(initialShipping);
  
  // Market is read-only — derived from locale
  const market = MARKETS[locale] || MARKETS.en;
  
  // Stats (from progress + briefs data)
  const stats = React.useMemo(() => {
    let modulesDone = 0;
    try {
      const raw = localStorage.getItem("chefverse_progress_v1");
      if (raw) {
        const p = JSON.parse(raw);
        modulesDone = Object.values(p || {}).filter(v => v && v.done).length;
      }
    } catch (e) {}
    let briefsDone = 0;
    try {
      const raw = localStorage.getItem("chefverse_briefs_v1");
      if (raw) {
        const p = JSON.parse(raw);
        briefsDone = Object.values(p || {}).filter(v => v === "submitted" || v === "approved").length;
      }
    } catch (e) {}
    if (modulesDone === 0 && window.__CHEFVERSE_PROFILE === "experienced") modulesDone = 4;
    if (briefsDone === 0 && window.__CHEFVERSE_PROFILE === "experienced") briefsDone = 2;
    return {
      modules: modulesDone,
      briefs: briefsDone,
      points: (modulesDone * 80) + (briefsDone * 150),
      streak: window.__CHEFVERSE_PROFILE === "experienced" ? 9 : 0,
    };
  }, []);
  
  const cancelEdit = (section) => {
    setEditingSection(null);
    if (section === "account") {
      setName(initialName);
      setEmail(initialEmail);
      setRoleKey(profile.role_key || "role_sous");
      setRestaurant(initialRestaurant);
      setYears(initialYears);
    } else if (section === "channels") {
      setChannels(initialChannels);
    } else if (section === "shipping") {
      setShipping(initialShipping);
    }
  };
  
  const handleSave = () => {
    setEditingSection(null);
    setSavedToast(true);
    setTimeout(() => setSavedToast(false), 2000);
  };
  
  const roleLabel = tl[roleKey] || (window.I18N[locale].onboard[roleKey] || roleKey);
  
  const roleOptions = ["role_chef", "role_sous", "role_owner", "role_pastry", "role_consult"];
  
  return (
    <div className="page profile-page">
      {/* Hero */}
      <div className="profile-hero">
        <div className="profile-hero-l">
          <div className="profile-avatar-big">
            <Avatar name={profile.name} initials={profile.initials} cls="" />
            <button className="profile-avatar-edit" type="button" title={tl.uploadAvatar} aria-label={tl.uploadAvatar}>
              <Icon name="camera" size={13} />
            </button>
          </div>
          <div className="profile-hero-info">
            <h1 className="profile-name">{name}</h1>
            <div className="profile-meta">
              <span className="profile-meta-pill">{roleLabel}</span>
              <span className="profile-meta-sep">·</span>
              <span className="profile-meta-market">
                <span className="profile-meta-flag">{market.flag}</span>
                {market.label}
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* Stats */}
      <section className="profile-section">
        <div className="profile-section-head">
          <div>
            <h2>{tl.yourStatsTitle}</h2>
            <p className="profile-section-sub">{tl.yourStatsSub}</p>
          </div>
        </div>
        <div className="profile-stats">
          <div className="profile-stat">
            <div className="profile-stat-icon" style={{ background: "var(--accent)", color: "var(--ufs-orange)" }}>
              <Icon name="award" size={18} />
            </div>
            <div>
              <div className="profile-stat-num">{stats.modules}</div>
              <div className="profile-stat-lab">{tl.statModulesDone}</div>
            </div>
          </div>
          <div className="profile-stat">
            <div className="profile-stat-icon" style={{ background: "rgba(91, 54, 87, 0.12)", color: "var(--aubergine, #5b3657)" }}>
              <Icon name="send" size={18} />
            </div>
            <div>
              <div className="profile-stat-num">{stats.briefs}</div>
              <div className="profile-stat-lab">{tl.statBriefsDone}</div>
            </div>
          </div>
          <div className="profile-stat">
            <div className="profile-stat-icon" style={{ background: "rgba(255, 90, 0, 0.14)", color: "var(--ufs-orange)" }}>
              <Icon name="gift" size={18} />
            </div>
            <div>
              <div className="profile-stat-num">{stats.points.toLocaleString()}</div>
              <div className="profile-stat-lab">{tl.statRewards}</div>
            </div>
          </div>
          <div className="profile-stat">
            <div className="profile-stat-icon" style={{ background: "rgba(21, 128, 61, 0.12)", color: "#15803d" }}>
              <Icon name="flame" size={18} />
            </div>
            <div>
              <div className="profile-stat-num">{stats.streak}</div>
              <div className="profile-stat-lab">{tl.statStreak}</div>
            </div>
          </div>
        </div>
      </section>

      {/* Account details — with Edit button next to heading */}
      <section className="profile-section">
        <div className="profile-section-head profile-section-head-row">
          <div>
            <h2>{tl.accountTitle}</h2>
            <p className="profile-section-sub">{tl.accountSub}</p>
          </div>
          <div className="profile-section-head-actions">
            {!editingAccount ? (
              <button className="btn btn-outline" onClick={() => setEditingSection("account")} disabled={editingSection !== null && !editingAccount}>
                <Icon name="edit" size={14} /> {tl.edit}
              </button>
            ) : (
              <>
                <button className="btn btn-outline" onClick={() => cancelEdit("account")}>{tl.cancel}</button>
                <button className="btn btn-primary" onClick={handleSave}>{tl.save}</button>
              </>
            )}
          </div>
        </div>
        <div className="profile-fields">
          <div className="profile-field">
            <label className="profile-label">{tl.fieldName}</label>
            {editingAccount
              ? <input className="profile-input" value={name} onChange={(e) => setName(e.target.value)} />
              : <div className="profile-value">{name}</div>}
          </div>
          <div className="profile-field">
            <label className="profile-label">{tl.fieldEmail}</label>
            {editingAccount
              ? <input className="profile-input" type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
              : <div className="profile-value">{email}</div>}
          </div>
          <div className="profile-field">
            <label className="profile-label">{tl.fieldRole}</label>
            {editingAccount
              ? <div className="profile-role-dd-wrap">
                  <UFSLocaleDropdown
                    value={roleKey}
                    onChange={setRoleKey}
                    ariaLabel="Select role"
                    fullWidth
                    options={roleOptions.map(rk => ({ value: rk, label: tl[rk] }))}
                  />
                </div>
              : <div className="profile-value">{roleLabel}</div>}
          </div>
          <div className="profile-field">
            <label className="profile-label">{tl.fieldRestaurant}</label>
            {editingAccount
              ? <input className="profile-input" value={restaurant} onChange={(e) => setRestaurant(e.target.value)}
                  placeholder={locale === "de" ? "Restaurant, Küche, eigene Marke oder freiberuflich" : locale === "id" ? "Restoran, dapur, brand pribadi, atau freelance" : "Restaurant, kitchen, personal brand, or freelance"} />
              : <div className="profile-value">{restaurant}</div>}
          </div>
          <div className="profile-field">
            <label className="profile-label">{tl.fieldYears}</label>
            {editingAccount
              ? <input className="profile-input" type="number" min="0" value={years} onChange={(e) => setYears(e.target.value)} />
              : <div className="profile-value">{years}</div>}
          </div>
          <div className="profile-field">
            <label className="profile-label">{tl.fieldMarket}</label>
            <div className="profile-value profile-value-readonly">
              <span className="profile-meta-flag">{market.flag}</span>
              {market.label}
            </div>
          </div>
        </div>
      </section>

      {/* Channels */}
      <section className="profile-section">
        <div className="profile-section-head profile-section-head-row">
          <div>
            <h2>{tl.channelsTitle}</h2>
            <p className="profile-section-sub">{tl.channelsSub}</p>
          </div>
          <div className="profile-section-head-actions">
            {!editingChannels ? (
              <button className="btn btn-outline" onClick={() => setEditingSection("channels")} disabled={editingSection !== null && !editingChannels}>
                <Icon name="edit" size={14} /> {tl.edit}
              </button>
            ) : (
              <>
                <button className="btn btn-outline" onClick={() => cancelEdit("channels")}>{tl.cancel}</button>
                <button className="btn btn-primary" onClick={handleSave}>{tl.save}</button>
              </>
            )}
          </div>
        </div>
        <div className="profile-fields">
          <div className="profile-field">
            <label className="profile-label"><Icon name="instagram" size={12} style={{ marginRight: 4, verticalAlign: "middle" }} />{tl.chInstagram}</label>
            {editingChannels
              ? <input className="profile-input" placeholder="@yourhandle" value={channels.instagram} onChange={(e) => setChannels({ ...channels, instagram: e.target.value })} />
              : <div className="profile-value">{channels.instagram || <span className="profile-empty">—</span>}</div>}
          </div>
          <div className="profile-field">
            <label className="profile-label"><Icon name="music" size={12} style={{ marginRight: 4, verticalAlign: "middle" }} />{tl.chTiktok}</label>
            {editingChannels
              ? <input className="profile-input" placeholder="@yourhandle" value={channels.tiktok} onChange={(e) => setChannels({ ...channels, tiktok: e.target.value })} />
              : <div className="profile-value">{channels.tiktok || <span className="profile-empty">—</span>}</div>}
          </div>
          <div className="profile-field">
            <label className="profile-label"><Icon name="facebook" size={12} style={{ marginRight: 4, verticalAlign: "middle" }} />{tl.chFacebook}</label>
            {editingChannels
              ? <input className="profile-input" placeholder="page name or URL" value={channels.facebook} onChange={(e) => setChannels({ ...channels, facebook: e.target.value })} />
              : <div className="profile-value">{channels.facebook || <span className="profile-empty">—</span>}</div>}
          </div>
          <div className="profile-field">
            <label className="profile-label"><Icon name="youtube" size={12} style={{ marginRight: 4, verticalAlign: "middle" }} />{tl.chYoutube}</label>
            {editingChannels
              ? <input className="profile-input" placeholder="@channelname" value={channels.youtube} onChange={(e) => setChannels({ ...channels, youtube: e.target.value })} />
              : <div className="profile-value">{channels.youtube || <span className="profile-empty">—</span>}</div>}
          </div>
        </div>
      </section>

      {/* Shipping address */}
      <section className="profile-section">
        <div className="profile-section-head profile-section-head-row">
          <div>
            <h2>{tl.shippingTitle}</h2>
            <p className="profile-section-sub">{tl.shippingSub}</p>
          </div>
          <div className="profile-section-head-actions">
            {!editingShipping ? (
              <button className="btn btn-outline" onClick={() => setEditingSection("shipping")} disabled={editingSection !== null && !editingShipping}>
                <Icon name="edit" size={14} /> {tl.edit}
              </button>
            ) : (
              <>
                <button className="btn btn-outline" onClick={() => cancelEdit("shipping")}>{tl.cancel}</button>
                <button className="btn btn-primary" onClick={handleSave}>{tl.save}</button>
              </>
            )}
          </div>
        </div>
        <div className="profile-fields profile-fields-shipping">
          <div className="profile-field profile-field-wide">
            <label className="profile-label">{tl.shipLine1}</label>
            {editingShipping
              ? <input className="profile-input" value={shipping.line1} onChange={(e) => setShipping({ ...shipping, line1: e.target.value })} />
              : <div className="profile-value">{shipping.line1 || <span className="profile-empty">—</span>}</div>}
          </div>
          <div className="profile-field profile-field-wide">
            <label className="profile-label">{tl.shipLine2}</label>
            {editingShipping
              ? <input className="profile-input" value={shipping.line2} onChange={(e) => setShipping({ ...shipping, line2: e.target.value })} />
              : <div className="profile-value">{shipping.line2 || <span className="profile-empty">—</span>}</div>}
          </div>
          <div className="profile-field">
            <label className="profile-label">{tl.shipCity}</label>
            {editingShipping
              ? <input className="profile-input" value={shipping.city} onChange={(e) => setShipping({ ...shipping, city: e.target.value })} />
              : <div className="profile-value">{shipping.city || <span className="profile-empty">—</span>}</div>}
          </div>
          <div className="profile-field">
            <label className="profile-label">{tl.shipPostal}</label>
            {editingShipping
              ? <input className="profile-input" value={shipping.postal} onChange={(e) => setShipping({ ...shipping, postal: e.target.value })} />
              : <div className="profile-value">{shipping.postal || <span className="profile-empty">—</span>}</div>}
          </div>
          <div className="profile-field">
            <label className="profile-label">{tl.shipRegion}</label>
            {editingShipping
              ? <input className="profile-input" value={shipping.region} onChange={(e) => setShipping({ ...shipping, region: e.target.value })} />
              : <div className="profile-value">{shipping.region || <span className="profile-empty">—</span>}</div>}
          </div>
          <div className="profile-field">
            <label className="profile-label">{tl.shipCountry}</label>
            {editingShipping
              ? <input className="profile-input" value={shipping.country} onChange={(e) => setShipping({ ...shipping, country: e.target.value })} />
              : <div className="profile-value">{shipping.country || <span className="profile-empty">—</span>}</div>}
          </div>
        </div>
      </section>

      {/* Password */}
      <section className="profile-section">
        <div className="profile-section-head">
          <div>
            <h2>{tl.pwTitle}</h2>
            <p className="profile-section-sub">{tl.pwSub}</p>
          </div>
        </div>
        <button className="btn btn-outline" onClick={onChangePassword}>
          <Icon name="lock" size={14} /> {tl.pwChange}
        </button>
      </section>

      {/* Danger zone */}
      <section className="profile-section profile-danger">
        <div className="profile-section-head">
          <div>
            <h2>{tl.dangerTitle}</h2>
            <p className="profile-section-sub">{tl.dangerSub}</p>
          </div>
        </div>
        <div className="profile-danger-actions">
          <button className="btn btn-outline profile-btn-danger">
            <Icon name="alert-triangle" size={14} /> {tl.dangerDelete}
          </button>
          <button className="btn btn-outline" onClick={onLogout}>
            <Icon name="log-out" size={14} /> {tl.dangerSignOut}
          </button>
        </div>
      </section>

      {savedToast && (
        <div className="profile-toast">
          <Icon name="check" size={14} /> {tl.saved}
        </div>
      )}
    </div>
  );
}

window.ProfilePage = ProfilePage;
window.PROFILE_I18N = PROFILE_I18N;
