// i18n strings + LocaleContext + useT
const STRINGS = {
  ro: {
    // brand / nav
    brand: "Silueta Nutrițională",
    nav_plans: "Pachete",
    nav_how: "Cum funcționează",
    nav_faq: "Întrebări",
    nav_login: "Autentificare",
    nav_dashboard: "Contul meu",
    nav_settings: "Setări",
    nav_logout: "Deconectare",
    nav_admin_dashboard: "Panou",
    nav_admin_clients: "Clienți",
    nav_admin_menus: "Meniuri",
    nav_admin_subs: "Abonamente",

    // landing
    landing_hero_title: "Meniuri personalizate.\nPe baza analizelor tale.",
    landing_hero_sub: "Un meniu de 7 zile creat pentru corpul tău, livrat la 14 zile, ajustat după analize, preferințe și starea ta de spirit.",
    landing_cta_primary: "Vezi pachetele",
    landing_cta_secondary: "Cum funcționează",
    landing_features_title: "De ce este altfel",
    feat1_title: "Personalizat după analize",
    feat1_body: "Vitamina D, hemoglobină, TSH — meniul tău se ajustează automat când lipsește ceva.",
    feat2_title: "Generat automat",
    feat2_body: "Algoritmul nostru combină alimente pe care le iubești, evită alergeni și echilibrează caloriile.",
    feat3_title: "Livrat la 14 zile",
    feat3_body: "Primești un meniu nou prin email și în cont, gata de imprimat sau salvat pe telefon.",
    how_title: "Cum funcționează",
    how_1_title: "Alegi un pachet",
    how_1_body: "Starter, Standard sau Premium — în funcție de cât timp vrei să fii însoțit.",
    how_2_title: "Completezi formularul",
    how_2_body: "Date generale, preferințe, alergii, analize de laborator și un test psihologic scurt.",
    how_3_title: "Primești meniul",
    how_3_body: "Un meniu de 7 zile, complet personalizat, cu mic dejun, prânz, cină și două gustări.",
    how_4_title: "Mănânci liniștit",
    how_4_body: "Reaprovizionezi la 14 zile. Actualizezi datele când e nevoie.",
    testimonials_title: "Ce spun clienții",
    faq_title: "Întrebări frecvente",
    faq_1_q: "Cât de des primesc un meniu nou?",
    faq_1_a: "La fiecare 14 zile primești un meniu nou pe 7 zile, prin email și în contul tău.",
    faq_2_q: "Trebuie să am analize de laborator?",
    faq_2_a: "Recomandăm analize din ultimele 6 luni. Dacă lipsesc, generăm meniul pe baza preferințelor și a obiectivului tău.",
    faq_3_q: "Pot anula oricând?",
    faq_3_a: "Da. Poți pune pe pauză sau anula din contul tău. Meniurile rămase se livrează până la finalul perioadei.",
    faq_4_q: "Cum este protejată confidențialitatea datelor?",
    faq_4_a: "Datele medicale sunt criptate și accesibile doar nutriționistului tău. Nu le partajăm cu terți.",

    // plans
    plans_title: "Alege pachetul potrivit",
    plans_sub: "Toate pachetele includ chestionarul complet, livrarea prin email și suport.",
    plan_starter: "Pachet Starter",
    plan_standard: "Pachet Standard",
    plan_premium: "Pachet Premium",
    plan_popular: "Cel mai popular",
    plan_buy: "Cumpără",
    plan_menus: (n) => `${n} meniuri`,
    plan_days: (n) => `${n} zile`,
    plan_lei: (n) => `${n} RON`,
    plan_cadence: "Livrare la 14 zile",

    // checkout
    checkout_demo: "Demo Stripe",
    checkout_title: "Finalizează plata",
    checkout_email: "Email",
    checkout_card: "Card",
    checkout_pay: "Plătește",
    checkout_cancel: "Renunță",
    checkout_secure: "Plată securizată — Demo",

    // success
    success_title: "Mulțumim!",
    success_sub: "Verifică emailul pentru linkul către contul tău.",
    success_email_preview: "Previzualizare email primit:",

    // signup
    signup_title: "Creează parola ta",
    signup_sub: "Setează o parolă pentru a accesa contul.",
    signup_password: "Parolă",
    signup_password_confirm: "Confirmă parola",
    signup_terms_label: "Sunt de acord cu",
    signup_terms_link: "Termenii și condițiile",
    signup_submit: "Activează contul",
    signup_eligible: "Eligibil pentru:",

    // login
    login_title: "Bine ai revenit",
    login_email: "Email",
    login_password: "Parolă",
    login_submit: "Intră în cont",
    login_forgot: "Ai uitat parola?",
    login_signup_helper: "Ai un cod de activare?",
    login_signup_link: "Activează contul",

    // forgot / reset
    forgot_title: "Resetează parola",
    forgot_sub: "Introdu emailul tău. Îți trimitem un link.",
    forgot_submit: "Trimite linkul",
    forgot_success: "Dacă există un cont cu acest email, ai primit un link de resetare.",
    reset_title: "Setează o parolă nouă",
    reset_new: "Parolă nouă",
    reset_confirm: "Confirmă parola",
    reset_submit: "Salvează parola",
    reset_success: "Parola a fost actualizată.",

    // terms
    terms_title: "Termeni și condiții",
    terms_disclaimer_title: "Important",
    terms_disclaimer: "Utilizatorul este responsabil pentru ceea ce consumă. Această aplicație generează recomandări pe baza datelor furnizate de utilizator. Aplicația nu este responsabilă dacă un alergen apare într-un meniu din cauza unor date lipsă, incorecte sau neactualizate de utilizator.",

    // emails
    email_subject: "Subiect",
    email_from: "De la",
    email_to: "Către",
    email_open_app: "Vezi în aplicație",
    email_activate: "Activează contul",
    email_renew: "Reînnoiește pachetul",
    email_reset: "Resetează parola",
    email_welcome_subject: "Bine ai venit — activează-ți contul",
    email_menu_subject: "Meniul tău pe 7 zile — Săptămâna 3",
    email_lab_subject: "Analizele tale expiră în 14 zile",
    email_renew_subject: "Pachetul tău s-a încheiat — reînnoiește",
    email_reset_subject: "Resetează-ți parola",
    emails_demo_btn: "Vezi emailuri demo",
    email_pdf_attached: "meniul-saptamana-3.pdf",

    // onboarding
    onb_step: (i, n) => `Pasul ${i} din ${n}`,
    onb_save: "Salvează și continuă mai târziu",
    onb_back: "Înapoi",
    onb_next: "Continuă",
    onb_finish: "Trimite formularul",
    onb_demo_first: "Prima dată",
    onb_demo_returning: "Abonament repetat",
    onb_demo_label: "Demo:",
    onb_validuntil: (date) => `Date valide până la ${date} — modifică dacă e nevoie`,
    onb_tc_reminder: "Ai acceptat T&C la activarea contului",
    onb_step1: "Date generale",
    onb_step2: "Preferințe alimentare",
    onb_step3: "Alergii",
    onb_step4: "Alimente neplăcute",
    onb_step5: "Băuturi neplăcute",
    onb_step6: "Analize de laborator",
    onb_step7: "Test psihologic",
    onb_height: "Înălțime (cm)",
    onb_dob: "Data nașterii",
    onb_sex: "Sex",
    onb_sex_f: "Feminin",
    onb_sex_m: "Masculin",
    onb_weight: "Greutate actuală (kg)",
    onb_activity: "Nivel de activitate",
    onb_goal: "Obiectiv",
    onb_wakeup: "Ora trezirii",
    onb_fasting: "Țin un post religios",
    onb_fasting_start: "Început post",
    onb_fasting_end: "Sfârșit post",
    onb_target_kcal: "Caloriile tale țintă",
    onb_kcal_per_day: "kcal/zi",
    onb_pref_vegan: "Vegan",
    onb_pref_vegetarian: "Vegetarian",
    onb_pref_lactose: "Intoleranță la lactoză",
    onb_pref_gluten: "Intoleranță la gluten",
    onb_pref_spicy: "Îmi place picantul",
    onb_allergies_helper: "Reconfirmă lista — alergiile se actualizează la 12 luni.",
    onb_search: "Caută…",
    onb_selected: (n) => `${n} selectate`,
    onb_lab_date: "Data analizelor",
    onb_lab_expired: "Analize expirate — efectuează analize noi pentru a continua.",
    onb_lab_upload: "Încarcă PDF analize",
    onb_psych_running: "Total curent",
    onb_psych_options: ["Deloc", "Câteva zile", "Mai mult de jumătate", "Aproape în fiecare zi"],

    // psych categories
    cat_anxiety: "Anxietate",
    cat_stress: "Stres",
    cat_sleep: "Somn",
    cat_energy: "Energie",
    cat_mood: "Dispoziție",

    // preferences (display names for nutritionist's profile view)
    pref_vegan: "Regim vegan",
    pref_vegetarian: "Regim vegetarian",
    pref_lactoseIntolerant: "Intoleranță la lactoză",
    pref_glutenIntolerant: "Intoleranță la gluten",
    pref_dislikesSpicy: "Evită mâncarea picantă",
    pref_likesSpicy: "Preferă mâncarea picantă",

    // psych answer scale
    psych_scale_0: "Niciodată",
    psych_scale_1: "Rar",
    psych_scale_2: "Uneori",
    psych_scale_3: "Des",
    psych_scale_4: "Aproape mereu",

    // lab categories
    lab_hepatic: "Hepatic",
    lab_renal: "Renal",
    lab_tumor: "Markeri tumorali",
    lab_cardiac: "Cardiac",
    lab_metabolic: "Metabolic",
    lab_hormonal: "Hormonal",
    lab_vitamins: "Vitamine",

    // status
    status_normal: "Normal",
    status_attention: "Atenție",
    status_outofrange: "În afara intervalului",
    status_valid: "Valid",
    status_expired: "Expirat",
    status_pending: "În așteptare",
    status_pending_update: "Actualizare necesară",
    status_active: "Activ",
    status_completed: "Încheiat",
    status_cancelled: "Anulat",
    status_paused: "Pe pauză",
    status_paid: "Plătit",
    status_refunded: "Rambursat",
    status_scheduled: "Programat",
    status_generated: "Generat",
    status_generating: "Se generează…",

    // onboarding complete
    onb_complete_title: "Datele tale au fost salvate.",
    onb_complete_sub: "Primul tău meniu va fi generat în 1–2 zile. Vei primi un email când e gata.",
    onb_complete_cta: "Vezi contul meu",

    // dashboard
    dash_hello: (name) => `Bună, ${name}!`,
    dash_waiting_title: "Pregătim primul tău meniu.",
    dash_waiting_helper: "Estimat: 1–2 zile. Vei primi un email când e gata.",
    dash_waiting_step_1: "Date primite",
    dash_waiting_step_2: "Generare meniu",
    dash_waiting_step_3: "Email cu PDF",
    dash_waiting_step_4: "Disponibil în cont",
    dash_active_sub: (days) => `Următorul meniu: ${days} zile`,
    dash_my_sub: "Abonamentul meu",
    dash_renew: "Reînnoiește",
    dash_renew_disabled: "Disponibil când abonamentul se încheie",
    dash_status_medical: "Status date medicale",
    dash_next_delivery: "Următoarea livrare",
    dash_history: "Istoricul meniurilor",
    dash_view_menu: "Vezi meniul",
    dash_download_pdf: "Descarcă PDF",
    dash_no_menus: "Nu ai încă meniuri generate",
    dash_reminder_pref_expiring: (days) => `Preferințele tale alimentare expiră în ${days} de zile — actualizează-le acum.`,
    dash_meniuri_progress: (a, b) => `${a} / ${b} meniuri livrate`,
    dash_end_date: (date) => `Se încheie pe ${date}`,
    dash_until: (date) => `valid până la ${date}`,
    dash_expires_in: (days) => `expiră în ${days} zile`,
    dash_update: "Actualizează",
    dash_week_n: (n) => `Săptămâna ${n}`,
    dash_dismiss: "Închide",

    // medical sub-rows
    med_lab: "Analize",
    med_psych: "Test psihologic",
    med_allergies: "Alergii",
    med_pref: "Preferințe",

    // menu viewer
    menu_back: "Înapoi la cont",
    menu_total: "Total zi",
    menu_total_kcal: (n) => `${n} kcal`,
    menu_send_email: "Trimite-mi pe email",
    menu_first_modal_title: "Înainte de a începe",
    menu_first_accept: "Am înțeles și sunt de acord",
    menu_continue: "Continuă",
    menu_why_title: "De ce această recomandare?",

    // ruleSource pills
    rs_lab: "lab",
    rs_psych: "psych",
    rs_preference: "pref.",
    rs_default: "default",

    // why explanation templates
    why_lab_vitd: "Această recomandare se bazează pe valoarea ta de Vitamina D = 15 ng/mL (deficit). Salmon, ouă și ciuperci sunt surse bune de vit. D.",
    why_psych_anxiety: "Recomandare calmantă pentru scor anxietate ridicat (10/15). Banane, ciocolată neagră și mușețel susțin starea de calm.",
    why_pref: "Aliment selectat conform preferințelor tale.",
    why_default: "Aliment de bază pentru echilibrul caloric și nutrițional.",

    // settings
    set_title: "Setări",
    set_profile: "Profil",
    set_lang: "Limbă",
    set_security: "Securitate",
    set_change: "Modificare",
    set_change_pass: "Schimbă parola",
    set_locked_tip: "Pentru a modifica datele stabile, contactează nutriționistul",
    set_lang_sub: "Limba afișată în aplicație",
    pwd_current: "Parola curentă",
    pwd_new: "Parolă nouă",
    pwd_confirm: "Confirmă parola",
    pwd_save: "Salvează",

    // billing
    bill_title: "Istoric facturi",
    bill_plan: "Pachet",
    bill_start: "Început",
    bill_end: "Sfârșit",
    bill_amount: "Sumă",
    bill_status: "Status plată",
    bill_invoice: "Factură",
    bill_download: "Descarcă",
    bill_empty: "Nu ai facturi încă.",

    // subscription mgmt
    sub_title: "Abonamentul meu",
    sub_pause: "Suspendă",
    sub_cancel: "Anulează",
    sub_resume: "Reia acum",
    sub_pause_title: "Suspendă abonamentul",
    sub_pause_until: "Reia la data:",
    sub_cancel_title: "Anulează abonamentul",
    sub_cancel_reason: "Motiv (opțional)",
    sub_cancel_warn: "Meniurile rămase se vor livra până la data de încheiere. Această acțiune este reversibilă în acest demo.",
    sub_demo_reset: "Demo: resetează abonament",
    sub_paused_banner: "Abonamentul tău este pe pauză.",
    sub_cancelled_banner: "Abonamentul tău a fost anulat. Meniurile rămase vor fi livrate până la data de încheiere.",
    confirm: "Confirmă",
    cancel: "Renunță",

    // renewal
    renew_title: (name) => `Bun-venit înapoi, ${name}!`,
    renew_sub: "Continuăm călătoria ta?",
    renew_valid_data: "Date valide",
    renew_must_update: "Trebuie reactualizate înainte de cumpărare:",
    renew_quickfix: "Actualizează acum",

    // lab expired blocking
    block_title: "Analizele tale au expirat",
    block_body: "Analizele tale de laborator au expirat. Te rugăm să introduci analize noi pentru a continua.",
    block_cta: "Adaugă analize noi",
    block_later: "Mai târziu",

    // admin
    adm_login_title: "Autentificare nutriționist",
    adm_dash_title: "Panou nutriționist",
    adm_kpi_clients: "Clienți activi",
    adm_kpi_subs: "Abonamente active",
    adm_kpi_menus_week: "Meniuri programate săptămâna asta",
    adm_kpi_expired: "Validări medicale expirate",
    adm_next_deliveries: "Următoarele livrări",
    adm_warnings: "Atenționări",
    adm_no_warnings: "Niciun client cu validări expirate.",
    adm_view: "Vezi",
    adm_clients_title: "Clienți",
    adm_filter_all: "Toți",
    adm_filter_active: "Activi",
    adm_filter_expired: "Expirate",
    adm_filter_paused: "Pe pauză",
    adm_col_name: "Nume",
    adm_col_email: "Email",
    adm_col_plan: "Plan curent",
    adm_col_remaining: "Meniuri rămase",
    adm_col_validation: "Validare medicală",
    adm_col_lastmenu: "Ultimul meniu",
    adm_col_status: "Status",
    adm_tab_profile: "Profil",
    adm_tab_subs: "Abonamente",
    adm_tab_labs: "Analize",
    adm_tab_psych: "Test psihologic",
    adm_tab_allergies: "Alergii și preferințe",
    adm_tab_menus: "Meniuri",
    adm_tab_freq: "Frecvență alimente",
    adm_tab_validations: "Validări medicale",
    adm_view_client_style: "Vezi în stilul clientului",
    adm_view_raw: "Vezi date brute",
    adm_freq_food: "Aliment",
    adm_freq_drink: "Băutură",
    adm_freq_last: "Ultima utilizare",
    adm_freq_30d: "Ultimele 30 zile",
    adm_freq_total: "Total",
    adm_menus_title: "Toate meniurile",
    adm_subs_title: "Abonamente / plăți",
    adm_modified_at: "Modificat:",

    // toasts
    toast_saved: "Salvat",
    toast_password_updated: "Parola a fost actualizată",
    toast_subscription_paused: "Abonament suspendat",
    toast_subscription_cancelled: "Abonament anulat",
    toast_subscription_resumed: "Abonament reluat",
    toast_email_sent: "Email trimis",
    toast_locale_changed: "Limba a fost schimbată",

    // empty
    empty_no_allergies: "Nicio alergie selectată",
    empty_no_subs: "Nu ai abonamente anterioare",

    // misc
    locale_label: "Limbă",
    locale_ro: "Română",
    locale_en: "English",
    yes: "Da",
    no: "Nu",
    optional: "(opțional)",
    required: "(obligatoriu)",
    close: "Închide",
    save: "Salvează",

    // demo mode
    demo_title: "Demo",
    demo_visitor: "Vizitator",
    demo_fresh: "Client — formular necompletat",
    demo_first: "Client — primul meniu",
    demo_active: "Client — abonament activ",
    demo_expired: "Client — analize expirate",
    demo_admin: "Nutriționist",
    demo_family: "Familie — selector profile",

    // family (concept stub)
    family_soon_badge: "În curând",
    family_soon_title: "Plan Familie",
    family_soon_subtitle: "Un cont, profile separate pentru fiecare membru al familiei. Fiecare profil are propriul formular, propriile analize și propriul meniu — cu reducere de pachet.",
    family_soon_cta: "Vezi schița conceptului",
    family_picker_title: "Cine completează formularul azi?",
    family_picker_sub: "Fiecare profil are propriul meniu, propriile analize și propriul test psihologic. Doar contul principal poate adăuga sau modifica profile.",
    family_owner_badge: "Cont principal",
    family_minor_badge: "Profil minor",
    family_add_profile: "Adaugă profil",
    family_demo_note: "Schiță de concept — flow-ul complet (subscripție partajată, intake per profil, validări medicale per profil, drepturi părinți–copii) este în lucru.",
    family_back_to_account: "Înapoi la cont",
    family_role_owner: "Mama (titulara contului)",
    family_role_partner: "Tata",
    family_role_child: "Copil",

    // activity
    act_sedentary: "Sedentar",
    act_sedentary_d: "Birou, foarte puțin sport",
    act_light: "Ușor",
    act_light_d: "1-2 antrenamente / săptămână",
    act_moderate: "Moderat",
    act_moderate_d: "3-4 antrenamente / săptămână",
    act_active: "Activ",
    act_active_d: "5+ antrenamente / săptămână",
    act_very: "Foarte activ",
    act_very_d: "Sport intens zilnic",

    // goals
    goal_lose: "Slăbire",
    goal_maintain: "Menținere",
    goal_muscle: "Masă musculară",
    goal_health: "Sănătate generală",

    // meal types
    meal_breakfast: "Mic dejun",
    meal_snack1: "Gustare 1",
    meal_snack_1: "Gustare 1",
    meal_lunch: "Prânz",
    meal_snack2: "Gustare 2",
    meal_snack_2: "Gustare 2",
    meal_dinner: "Cină",

    // weekdays
    days_short: ["Lu", "Ma", "Mi", "Jo", "Vi", "Sâ", "Du"],
    days_long: ["Luni", "Marți", "Miercuri", "Joi", "Vineri", "Sâmbătă", "Duminică"],
    months: ["Ian", "Feb", "Mar", "Apr", "Mai", "Iun", "Iul", "Aug", "Sep", "Oct", "Noi", "Dec"],

    // --- additions ---
    adm_back_clients: "← Toți clienții",
    adm_clients: "Clienți",
    adm_clients_count: (n) => `${n} clienți`,
    adm_dash_sub: "Privire de ansamblu — clienți, livrări și atenționări.",
    adm_disliked: "Neplăcute",
    adm_disliked_drinks: "Băuturi neplăcute",
    adm_disliked_foods: "Alimente neplăcute",
    adm_kpi_menus: "Meniuri săptămâna asta",
    adm_lab_date: "Data analizelor",
    adm_menus: "Meniuri",
    adm_psych_summary: "Rezumat test psihologic",
    adm_search_clients: "Caută clienți…",
    adm_see_all: "Vezi tot",
    adm_status_generated: "Generat",
    adm_status_scheduled: "Programat",
    adm_subs: "Abonamente",
    adm_subs_count: (n) => `${n} abonamente`,
    adm_tab_frequency: "Frecvență alimente",
    adm_th_30days: "Ultimele 30 zile",
    adm_th_actions: "Acțiuni",
    adm_th_client: "Client",
    adm_th_delivered: "Livrate",
    adm_th_field: "Câmp",
    adm_th_item: "Element",
    adm_th_last_menu: "Ultimul meniu",
    adm_th_last_update: "Ultima actualizare",
    adm_th_last_used: "Ultima utilizare",
    adm_th_modified: "Modificat",
    adm_th_name: "Nume",
    adm_th_next_required: "Următoarea actualizare",
    adm_th_payment: "Plată",
    adm_th_plan: "Plan",
    adm_th_remaining: "Rămase",
    adm_th_status: "Status",
    adm_th_total: "Total",
    adm_th_trend: "Tendință",
    adm_th_validation: "Validare",
    adm_th_value: "Valoare",
    adm_upcoming: "Următoarele livrări",
    adm_view_client: "Vezi client",
    adm_view_menu: "Vezi meniu",
    back: "Înapoi",
    back_to_dashboard: "← Înapoi la cont",
    billing_invoice: "Factură",
    billing_invoice_dl: "Descarcă",
    billing_sub: "Toate plățile pentru abonamentele tale.",
    billing_th_amount: "Sumă",
    billing_th_end: "Sfârșit",
    billing_th_invoice: "Factură",
    billing_th_payment: "Plată",
    billing_th_plan: "Plan",
    billing_th_start: "Început",
    billing_th_status: "Status",
    billing_title: "Istoric facturi",
    dash_active_helper: (days) => `Următorul meniu sosește în ${days} zile.`,
    dash_empty_menu: "Nu ai încă meniuri generate.",
    dash_first_eta: "Estimat: 1–2 zile",
    dash_first_helper: "Vei primi un email când e gata.",
    dash_hello_label: "Bună,",
    dash_hi: (name) => `Bună, ${name}!`,
    dash_hi_first: (name) => `Bună, ${name}! Pregătim primul tău meniu.`,
    dash_in: (days) => `în ${days} zile`,
    dash_menu_history: "Istoricul meniurilor",
    dash_menus_delivered: (a, b) => `${a} / ${b} meniuri livrate`,
    dash_reminder_banner: (days) => `Preferințele tale alimentare expiră în ${days} de zile — actualizează-le acum.`,
    dash_renew_disabled_tip: "Disponibil când abonamentul se încheie",
    dash_settings: "Setări",
    dash_status_app: "Disponibil în cont",
    dash_status_data: "Date primite",
    dash_status_email: "Email cu PDF",
    dash_status_gen: "Generare meniu",
    dash_subscription: "Abonamentul meu",
    dash_th_actions: "Acțiuni",
    dash_th_period: "Perioadă",
    dash_th_status: "Status",
    dash_th_week: "Săptămână",
    dash_validations: "Status date medicale",
    dash_view: "Vezi",
    days: "zile",
    filter_active: "Activi",
    filter_all: "Toți",
    filter_expired: "Expirate",
    filter_paused: "Pe pauză",
    lab_block_body: "Analizele tale de laborator au expirat. Te rugăm să introduci analize noi pentru a continua.",
    lab_block_cta: "Adaugă analize noi",
    lab_block_later: "Mai târziu",
    lab_block_title: "Analizele tale au expirat",
    macro_carbs: "Carbohidrați",
    macro_fat: "Grăsimi",
    macro_protein: "Proteine",
    meals: "Mese",
    menu_accept_check: "Am înțeles și sunt de acord",
    menu_accept_continue: "Continuă",
    menu_accept_title: "Înainte de a începe",
    menu_download: "Descarcă PDF",
    menu_for: (name) => `Meniul pentru ${name}`,
    menu_macros: "Macronutrienți",
    menu_send_btn: "Trimite-mi pe email",
    menu_send_helper: "Vei primi PDF-ul pe adresa contului.",
    menu_sent: "Email trimis",
    menu_total_day: "Total zi",
    menu_week: (n) => `Săptămâna ${n}`,
    pay_paid: "Plătit",
    pay_pending: "În așteptare",
    pay_refunded: "Rambursat",
    renew_fix: "Actualizează",
    renew_to_update: "Trebuie reactualizate înainte de cumpărare:",
    renew_welcome_back: (name) => `Bun-venit înapoi, ${name}!`,
    rule_default_explain: "Aliment de bază pentru echilibrul caloric și nutrițional.",
    set_billing: "Istoric facturi",
    set_change_email: "Schimbă emailul",
    set_change_pwd: "Schimbă parola",
    set_confirm_pwd: "Confirmă parola",
    set_current_pwd: "Parola curentă",
    set_dob: "Data nașterii",
    set_edit: "Modifică",
    set_email: "Email",
    set_height: "Înălțime",
    set_language: "Limbă",
    set_language_helper: "Limba afișată în aplicație",
    set_logout: "Deconectează-te",
    set_name: "Nume",
    set_new_email: "Email nou",
    set_new_pwd: "Parolă nouă",
    set_sex: "Sex",
    set_sub: "Profil, limbă și securitate.",
    set_sub_mgmt: "Gestionează abonamentul",
    status_delivered: "Livrat",
    status_generating_short: "Se generează",
    sub_cancel_confirm: "Da, anulează",
    sub_cancel_warning: "Meniurile rămase se vor livra până la data de încheiere.",
    sub_mgmt_sub: "Pune pe pauză sau anulează — reversibil în acest demo.",
    sub_mgmt_title: "Gestionează abonamentul",
    sub_pause_confirm: "Suspendă",
    sub_pause_helper: "Alege data la care abonamentul reia automat (max. 60 de zile).",
    sub_resume_at: (date) => `Reia la ${date}`,
    sub_resume_now: "Reia acum",
    val_allergies: "Alergii",
    val_expired: "Expirat",
    val_expiring: (days) => `expiră în ${days} zile`,
    val_lab: "Analize",
    val_lab_expired: "Analize expirate",
    val_pending: "În așteptare",
    val_prefs: "Preferințe",
    val_psych: "Test psihologic",
    val_update: "Actualizează",
    val_valid: "Valid",
    val_valid_until: (date) => `valid până la ${date}`,
  },

  en: {
    brand: "Silueta Nutrițională",
    nav_plans: "Plans",
    nav_how: "How it works",
    nav_faq: "FAQ",
    nav_login: "Log in",
    nav_dashboard: "My account",
    nav_settings: "Settings",
    nav_logout: "Log out",
    nav_admin_dashboard: "Dashboard",
    nav_admin_clients: "Clients",
    nav_admin_menus: "Menus",
    nav_admin_subs: "Subscriptions",

    landing_hero_title: "Personalized menus.\nBased on your lab results.",
    landing_hero_sub: "A 7-day menu built for your body, delivered every 14 days, tuned to your labs, preferences and mood.",
    landing_cta_primary: "See plans",
    landing_cta_secondary: "How it works",
    landing_features_title: "Why it's different",
    feat1_title: "Personalized to your labs",
    feat1_body: "Vitamin D, hemoglobin, TSH — your menu adjusts when something is off.",
    feat2_title: "Auto-generated",
    feat2_body: "Our algorithm mixes foods you love, avoids allergens, balances calories.",
    feat3_title: "Delivered every 14 days",
    feat3_body: "A new menu in your inbox and account, ready to print or save on your phone.",
    how_title: "How it works",
    how_1_title: "Choose a plan",
    how_1_body: "Starter, Standard or Premium — based on how long you want to be guided.",
    how_2_title: "Fill in the form",
    how_2_body: "Profile, preferences, allergies, lab results and a short psych check-in.",
    how_3_title: "Get your menu",
    how_3_body: "A fully personalized 7-day menu — breakfast, lunch, dinner and two snacks.",
    how_4_title: "Eat with peace of mind",
    how_4_body: "Refresh every 14 days. Update your data when it changes.",
    testimonials_title: "What clients say",
    faq_title: "Frequently asked",
    faq_1_q: "How often do I get a new menu?",
    faq_1_a: "Every 14 days you receive a fresh 7-day menu via email and in your account.",
    faq_2_q: "Do I need lab results?",
    faq_2_a: "We recommend labs from the past 6 months. If missing, we generate from preferences and goals.",
    faq_3_q: "Can I cancel anytime?",
    faq_3_a: "Yes. You can pause or cancel from your account. Remaining menus are delivered to the end of the period.",
    faq_4_q: "How is my data protected?",
    faq_4_a: "Medical data is encrypted and only your nutritionist can access it. We never share with third parties.",

    plans_title: "Choose the right plan",
    plans_sub: "All plans include the full questionnaire, email delivery and support.",
    plan_starter: "Starter Plan",
    plan_standard: "Standard Plan",
    plan_premium: "Premium Plan",
    plan_popular: "Most popular",
    plan_buy: "Buy",
    plan_menus: (n) => `${n} menus`,
    plan_days: (n) => `${n} days`,
    plan_lei: (n) => `${n} RON`,
    plan_cadence: "Delivered every 14 days",

    checkout_demo: "Demo Stripe",
    checkout_title: "Complete payment",
    checkout_email: "Email",
    checkout_card: "Card",
    checkout_pay: "Pay",
    checkout_cancel: "Cancel",
    checkout_secure: "Secure payment — Demo",

    success_title: "Thank you!",
    success_sub: "Check your inbox for the link to your account.",
    success_email_preview: "Preview of your email:",

    signup_title: "Set your password",
    signup_sub: "Choose a password to access your account.",
    signup_password: "Password",
    signup_password_confirm: "Confirm password",
    signup_terms_label: "I agree with",
    signup_terms_link: "the Terms & Conditions",
    signup_submit: "Activate account",
    signup_eligible: "Eligible for:",

    login_title: "Welcome back",
    login_email: "Email",
    login_password: "Password",
    login_submit: "Log in",
    login_forgot: "Forgot password?",
    login_signup_helper: "Have an activation code?",
    login_signup_link: "Activate account",

    forgot_title: "Reset your password",
    forgot_sub: "Enter your email. We'll send you a link.",
    forgot_submit: "Send link",
    forgot_success: "If an account exists for this email, you've received a reset link.",
    reset_title: "Set a new password",
    reset_new: "New password",
    reset_confirm: "Confirm password",
    reset_submit: "Save password",
    reset_success: "Your password was updated.",

    terms_title: "Terms & Conditions",
    terms_disclaimer_title: "Important",
    terms_disclaimer: "The user is responsible for what they consume. This app generates recommendations based on the data provided by the user. The app is not responsible if an allergen appears in a menu due to missing, incorrect or outdated user data.",

    email_subject: "Subject",
    email_from: "From",
    email_to: "To",
    email_open_app: "Open in app",
    email_activate: "Activate account",
    email_renew: "Renew plan",
    email_reset: "Reset password",
    email_welcome_subject: "Welcome — activate your account",
    email_menu_subject: "Your 7-day menu — Week 3",
    email_lab_subject: "Your labs expire in 14 days",
    email_renew_subject: "Your plan ended — renew",
    email_reset_subject: "Reset your password",
    emails_demo_btn: "See demo emails",
    email_pdf_attached: "menu-week-3.pdf",

    onb_step: (i, n) => `Step ${i} of ${n}`,
    onb_save: "Save and continue later",
    onb_back: "Back",
    onb_next: "Continue",
    onb_finish: "Submit form",
    onb_demo_first: "First time",
    onb_demo_returning: "Returning",
    onb_demo_label: "Demo:",
    onb_validuntil: (date) => `Valid until ${date} — edit if needed`,
    onb_tc_reminder: "You accepted T&C at account activation",
    onb_step1: "Profile",
    onb_step2: "Food preferences",
    onb_step3: "Allergies",
    onb_step4: "Disliked foods",
    onb_step5: "Disliked drinks",
    onb_step6: "Lab results",
    onb_step7: "Psych check-in",
    onb_height: "Height (cm)",
    onb_dob: "Date of birth",
    onb_sex: "Sex",
    onb_sex_f: "Female",
    onb_sex_m: "Male",
    onb_weight: "Current weight (kg)",
    onb_activity: "Activity level",
    onb_goal: "Goal",
    onb_wakeup: "Wake-up time",
    onb_fasting: "I follow a religious fast",
    onb_fasting_start: "Fast start",
    onb_fasting_end: "Fast end",
    onb_target_kcal: "Your target calories",
    onb_kcal_per_day: "kcal/day",
    onb_pref_vegan: "Vegan",
    onb_pref_vegetarian: "Vegetarian",
    onb_pref_lactose: "Lactose intolerant",
    onb_pref_gluten: "Gluten intolerant",
    onb_pref_spicy: "I like spicy food",
    onb_allergies_helper: "Re-confirm the list — allergies are refreshed every 12 months.",
    onb_search: "Search…",
    onb_selected: (n) => `${n} selected`,
    onb_lab_date: "Lab date",
    onb_lab_expired: "Labs expired — submit new labs to continue.",
    onb_lab_upload: "Upload lab PDF",
    onb_psych_running: "Running total",
    onb_psych_options: ["Not at all", "A few days", "More than half", "Nearly every day"],

    cat_anxiety: "Anxiety",
    cat_stress: "Stress",
    cat_sleep: "Sleep",
    cat_energy: "Energy",
    cat_mood: "Mood",

    pref_vegan: "Vegan diet",
    pref_vegetarian: "Vegetarian diet",
    pref_lactoseIntolerant: "Lactose intolerant",
    pref_glutenIntolerant: "Gluten intolerant",
    pref_dislikesSpicy: "Avoids spicy food",
    pref_likesSpicy: "Enjoys spicy food",

    psych_scale_0: "Never",
    psych_scale_1: "Rarely",
    psych_scale_2: "Sometimes",
    psych_scale_3: "Often",
    psych_scale_4: "Almost always",

    lab_hepatic: "Hepatic",
    lab_renal: "Renal",
    lab_tumor: "Tumor markers",
    lab_cardiac: "Cardiac",
    lab_metabolic: "Metabolic",
    lab_hormonal: "Hormonal",
    lab_vitamins: "Vitamins",

    status_normal: "Normal",
    status_attention: "Attention",
    status_outofrange: "Out of range",
    status_valid: "Valid",
    status_expired: "Expired",
    status_pending: "Pending",
    status_pending_update: "Update needed",
    status_active: "Active",
    status_completed: "Completed",
    status_cancelled: "Cancelled",
    status_paused: "Paused",
    status_paid: "Paid",
    status_refunded: "Refunded",
    status_scheduled: "Scheduled",
    status_generated: "Generated",
    status_generating: "Generating…",

    onb_complete_title: "Your data has been saved.",
    onb_complete_sub: "Your first menu will be generated in 1–2 days. We'll email you when it's ready.",
    onb_complete_cta: "Go to my account",

    dash_hello: (name) => `Hi, ${name}!`,
    dash_waiting_title: "We're preparing your first menu.",
    dash_waiting_helper: "Estimated: 1–2 days. We'll email you when it's ready.",
    dash_waiting_step_1: "Data received",
    dash_waiting_step_2: "Generating menu",
    dash_waiting_step_3: "Email with PDF",
    dash_waiting_step_4: "Available in account",
    dash_active_sub: (days) => `Next menu: ${days} days`,
    dash_my_sub: "My subscription",
    dash_renew: "Renew",
    dash_renew_disabled: "Available when subscription ends",
    dash_status_medical: "Medical data status",
    dash_next_delivery: "Next delivery",
    dash_history: "Menu history",
    dash_view_menu: "View menu",
    dash_download_pdf: "Download PDF",
    dash_no_menus: "No menus yet",
    dash_reminder_pref_expiring: (days) => `Your food preferences expire in ${days} days — update them now.`,
    dash_meniuri_progress: (a, b) => `${a} / ${b} menus delivered`,
    dash_end_date: (date) => `Ends on ${date}`,
    dash_until: (date) => `valid until ${date}`,
    dash_expires_in: (days) => `expires in ${days} days`,
    dash_update: "Update",
    dash_week_n: (n) => `Week ${n}`,
    dash_dismiss: "Dismiss",

    med_lab: "Labs",
    med_psych: "Psych check",
    med_allergies: "Allergies",
    med_pref: "Preferences",

    menu_back: "Back to account",
    menu_total: "Day total",
    menu_total_kcal: (n) => `${n} kcal`,
    menu_send_email: "Email it to me",
    menu_first_modal_title: "Before you start",
    menu_first_accept: "I understand and agree",
    menu_continue: "Continue",
    menu_why_title: "Why this recommendation?",

    rs_lab: "lab",
    rs_psych: "psych",
    rs_preference: "pref.",
    rs_default: "default",

    why_lab_vitd: "This recommendation is based on your Vitamin D = 15 ng/mL (deficit). Salmon, eggs and mushrooms are good sources of vit. D.",
    why_psych_anxiety: "Calming choice for high anxiety score (10/15). Bananas, dark chocolate and chamomile support calm.",
    why_pref: "Food selected based on your preferences.",
    why_default: "Staple food for caloric and nutritional balance.",

    set_title: "Settings",
    set_profile: "Profile",
    set_lang: "Language",
    set_security: "Security",
    set_change: "Edit",
    set_change_pass: "Change password",
    set_locked_tip: "To edit stable data, contact your nutritionist",
    set_lang_sub: "Language shown in the app",
    pwd_current: "Current password",
    pwd_new: "New password",
    pwd_confirm: "Confirm password",
    pwd_save: "Save",

    bill_title: "Billing history",
    bill_plan: "Plan",
    bill_start: "Start",
    bill_end: "End",
    bill_amount: "Amount",
    bill_status: "Payment status",
    bill_invoice: "Invoice",
    bill_download: "Download",
    bill_empty: "No invoices yet.",

    sub_title: "My subscription",
    sub_pause: "Pause",
    sub_cancel: "Cancel",
    sub_resume: "Resume now",
    sub_pause_title: "Pause subscription",
    sub_pause_until: "Resume on:",
    sub_cancel_title: "Cancel subscription",
    sub_cancel_reason: "Reason (optional)",
    sub_cancel_warn: "Remaining menus will be delivered to the end of the period. This action is reversible in this demo.",
    sub_demo_reset: "Demo: reset subscription",
    sub_paused_banner: "Your subscription is paused.",
    sub_cancelled_banner: "Your subscription was cancelled. Remaining menus will be delivered until the end date.",
    confirm: "Confirm",
    cancel: "Cancel",

    renew_title: (name) => `Welcome back, ${name}!`,
    renew_sub: "Shall we continue your journey?",
    renew_valid_data: "Valid data",
    renew_must_update: "Must be updated before purchase:",
    renew_quickfix: "Update now",

    block_title: "Your labs have expired",
    block_body: "Your lab results have expired. Please submit new labs to continue.",
    block_cta: "Add new labs",
    block_later: "Later",

    adm_login_title: "Nutritionist login",
    adm_dash_title: "Nutritionist dashboard",
    adm_kpi_clients: "Active clients",
    adm_kpi_subs: "Active subscriptions",
    adm_kpi_menus_week: "Menus this week",
    adm_kpi_expired: "Expired medical validations",
    adm_next_deliveries: "Upcoming deliveries",
    adm_warnings: "Warnings",
    adm_no_warnings: "No clients with expired validations.",
    adm_view: "View",
    adm_clients_title: "Clients",
    adm_filter_all: "All",
    adm_filter_active: "Active",
    adm_filter_expired: "Expired",
    adm_filter_paused: "Paused",
    adm_col_name: "Name",
    adm_col_email: "Email",
    adm_col_plan: "Current plan",
    adm_col_remaining: "Menus remaining",
    adm_col_validation: "Medical validation",
    adm_col_lastmenu: "Last menu",
    adm_col_status: "Status",
    adm_tab_profile: "Profile",
    adm_tab_subs: "Subscriptions",
    adm_tab_labs: "Labs",
    adm_tab_psych: "Psych check",
    adm_tab_allergies: "Allergies & prefs",
    adm_tab_menus: "Menus",
    adm_tab_freq: "Food frequency",
    adm_tab_validations: "Medical validations",
    adm_view_client_style: "Client view",
    adm_view_raw: "Raw data",
    adm_freq_food: "Food",
    adm_freq_drink: "Drink",
    adm_freq_last: "Last used",
    adm_freq_30d: "Last 30 days",
    adm_freq_total: "Total",
    adm_menus_title: "All menus",
    adm_subs_title: "Subscriptions / payments",
    adm_modified_at: "Modified:",

    toast_saved: "Saved",
    toast_password_updated: "Password updated",
    toast_subscription_paused: "Subscription paused",
    toast_subscription_cancelled: "Subscription cancelled",
    toast_subscription_resumed: "Subscription resumed",
    toast_email_sent: "Email sent",
    toast_locale_changed: "Language changed",

    empty_no_allergies: "No allergies selected",
    empty_no_subs: "No previous subscriptions",

    locale_label: "Language",
    locale_ro: "Română",
    locale_en: "English",
    yes: "Yes",
    no: "No",
    optional: "(optional)",
    required: "(required)",
    close: "Close",
    save: "Save",

    demo_title: "Demo",
    demo_visitor: "Visitor",
    demo_fresh: "Client — form not filled",
    demo_first: "Client — first menu",
    demo_active: "Client — active subscription",
    demo_expired: "Client — expired labs",
    demo_admin: "Nutritionist",
    demo_family: "Family — profile picker",

    family_soon_badge: "Coming soon",
    family_soon_title: "Family Plan",
    family_soon_subtitle: "One account, separate profiles for each family member. Each profile has its own form, lab tests and menu — with a bundle discount.",
    family_soon_cta: "Preview the concept",
    family_picker_title: "Who's filling in today?",
    family_picker_sub: "Each profile has its own menu, lab tests and psychological assessment. Only the head account can add or modify profiles.",
    family_owner_badge: "Account owner",
    family_minor_badge: "Minor profile",
    family_add_profile: "Add profile",
    family_demo_note: "Concept sketch — the full flow (shared subscription, per-profile intake, per-profile medical validations, parent–child permissions) is in design.",
    family_back_to_account: "Back to account",
    family_role_owner: "Mother (account owner)",
    family_role_partner: "Father",
    family_role_child: "Child",

    act_sedentary: "Sedentary",
    act_sedentary_d: "Desk job, very little sport",
    act_light: "Light",
    act_light_d: "1-2 workouts / week",
    act_moderate: "Moderate",
    act_moderate_d: "3-4 workouts / week",
    act_active: "Active",
    act_active_d: "5+ workouts / week",
    act_very: "Very active",
    act_very_d: "Intense daily sport",

    goal_lose: "Lose weight",
    goal_maintain: "Maintain",
    goal_muscle: "Gain muscle",
    goal_health: "General health",

    meal_breakfast: "Breakfast",
    meal_snack1: "Snack 1",
    meal_snack_1: "Snack 1",
    meal_lunch: "Lunch",
    meal_snack2: "Snack 2",
    meal_snack_2: "Snack 2",
    meal_dinner: "Dinner",

    days_short: ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
    days_long: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
    months: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],

    // --- additions ---
    adm_back_clients: "← All clients",
    adm_clients: "Clients",
    adm_clients_count: (n) => `${n} clients`,
    adm_dash_sub: "At-a-glance — clients, deliveries and warnings.",
    adm_disliked: "Disliked",
    adm_disliked_drinks: "Disliked drinks",
    adm_disliked_foods: "Disliked foods",
    adm_kpi_menus: "Menus this week",
    adm_lab_date: "Lab date",
    adm_menus: "Menus",
    adm_psych_summary: "Psych check summary",
    adm_search_clients: "Search clients…",
    adm_see_all: "See all",
    adm_status_generated: "Generated",
    adm_status_scheduled: "Scheduled",
    adm_subs: "Subscriptions",
    adm_subs_count: (n) => `${n} subscriptions`,
    adm_tab_frequency: "Food frequency",
    adm_th_30days: "Last 30 days",
    adm_th_actions: "Actions",
    adm_th_client: "Client",
    adm_th_delivered: "Delivered",
    adm_th_field: "Field",
    adm_th_item: "Item",
    adm_th_last_menu: "Last menu",
    adm_th_last_update: "Last update",
    adm_th_last_used: "Last used",
    adm_th_modified: "Modified",
    adm_th_name: "Name",
    adm_th_next_required: "Next required",
    adm_th_payment: "Payment",
    adm_th_plan: "Plan",
    adm_th_remaining: "Remaining",
    adm_th_status: "Status",
    adm_th_total: "Total",
    adm_th_trend: "Trend",
    adm_th_validation: "Validation",
    adm_th_value: "Value",
    adm_upcoming: "Upcoming deliveries",
    adm_view_client: "View client",
    adm_view_menu: "View menu",
    back: "Back",
    back_to_dashboard: "← Back to account",
    billing_invoice: "Invoice",
    billing_invoice_dl: "Download",
    billing_sub: "All payments for your subscriptions.",
    billing_th_amount: "Amount",
    billing_th_end: "End",
    billing_th_invoice: "Invoice",
    billing_th_payment: "Payment",
    billing_th_plan: "Plan",
    billing_th_start: "Start",
    billing_th_status: "Status",
    billing_title: "Billing history",
    dash_active_helper: (days) => `Your next menu arrives in ${days} days.`,
    dash_empty_menu: "No menus generated yet.",
    dash_first_eta: "Estimated: 1–2 days",
    dash_first_helper: "We'll email you when it's ready.",
    dash_hello_label: "Hi,",
    dash_hi: (name) => `Hi, ${name}!`,
    dash_hi_first: (name) => `Hi, ${name}! We're preparing your first menu.`,
    dash_in: (days) => `in ${days} days`,
    dash_menu_history: "Menu history",
    dash_menus_delivered: (a, b) => `${a} / ${b} menus delivered`,
    dash_reminder_banner: (days) => `Your food preferences expire in ${days} days — update them now.`,
    dash_renew_disabled_tip: "Available when subscription ends",
    dash_settings: "Settings",
    dash_status_app: "Available in account",
    dash_status_data: "Data received",
    dash_status_email: "Email with PDF",
    dash_status_gen: "Generating menu",
    dash_subscription: "My subscription",
    dash_th_actions: "Actions",
    dash_th_period: "Period",
    dash_th_status: "Status",
    dash_th_week: "Week",
    dash_validations: "Medical data status",
    dash_view: "View",
    days: "days",
    filter_active: "Active",
    filter_all: "All",
    filter_expired: "Expired",
    filter_paused: "Paused",
    lab_block_body: "Your lab results have expired. Please submit new labs to continue.",
    lab_block_cta: "Add new labs",
    lab_block_later: "Later",
    lab_block_title: "Your labs have expired",
    macro_carbs: "Carbs",
    macro_fat: "Fat",
    macro_protein: "Protein",
    meals: "Meals",
    menu_accept_check: "I understand and agree",
    menu_accept_continue: "Continue",
    menu_accept_title: "Before you start",
    menu_download: "Download PDF",
    menu_for: (name) => `Menu for ${name}`,
    menu_macros: "Macros",
    menu_send_btn: "Email it to me",
    menu_send_helper: "We'll send the PDF to your account email.",
    menu_sent: "Email sent",
    menu_total_day: "Day total",
    menu_week: (n) => `Week ${n}`,
    pay_paid: "Paid",
    pay_pending: "Pending",
    pay_refunded: "Refunded",
    renew_fix: "Update",
    renew_to_update: "Must be updated before purchase:",
    renew_welcome_back: (name) => `Welcome back, ${name}!`,
    rule_default_explain: "Staple food for caloric and nutritional balance.",
    set_billing: "Billing history",
    set_change_email: "Change email",
    set_change_pwd: "Change password",
    set_confirm_pwd: "Confirm password",
    set_current_pwd: "Current password",
    set_dob: "Date of birth",
    set_edit: "Edit",
    set_email: "Email",
    set_height: "Height",
    set_language: "Language",
    set_language_helper: "Language shown in the app",
    set_logout: "Log out",
    set_name: "Name",
    set_new_email: "New email",
    set_new_pwd: "New password",
    set_sex: "Sex",
    set_sub: "Profile, language and security.",
    set_sub_mgmt: "Manage subscription",
    status_delivered: "Delivered",
    status_generating_short: "Generating",
    sub_cancel_confirm: "Yes, cancel",
    sub_cancel_warning: "Remaining menus will be delivered until the end date.",
    sub_mgmt_sub: "Pause or cancel — reversible in this demo.",
    sub_mgmt_title: "Manage subscription",
    sub_pause_confirm: "Pause",
    sub_pause_helper: "Pick the date the subscription resumes (max. 60 days).",
    sub_resume_at: (date) => `Resume on ${date}`,
    sub_resume_now: "Resume now",
    val_allergies: "Allergies",
    val_expired: "Expired",
    val_expiring: (days) => `expires in ${days} days`,
    val_lab: "Labs",
    val_lab_expired: "Labs expired",
    val_pending: "Pending",
    val_prefs: "Preferences",
    val_psych: "Psych check",
    val_update: "Update",
    val_valid: "Valid",
    val_valid_until: (date) => `valid until ${date}`,
  },
};

const LocaleContext = React.createContext({ locale: 'ro', setLocale: () => {} });

function LocaleProvider({ children }) {
  const [locale, setLocaleState] = React.useState(() => {
    try { return localStorage.getItem('app.locale') || 'ro'; } catch (e) { return 'ro'; }
  });
  const setLocale = React.useCallback((l) => {
    setLocaleState(l);
    try { localStorage.setItem('app.locale', l); } catch (e) {}
    document.documentElement.lang = l;
  }, []);
  React.useEffect(() => { document.documentElement.lang = locale; }, [locale]);
  return <LocaleContext.Provider value={{ locale, setLocale }}>{children}</LocaleContext.Provider>;
}

function useT() {
  const { locale } = React.useContext(LocaleContext);
  const dict = STRINGS[locale];
  return (key, ...args) => {
    const v = dict[key];
    if (typeof v === 'function') return v(...args);
    if (v === undefined) return key;
    return v;
  };
}

function useLocale() {
  return React.useContext(LocaleContext);
}

Object.assign(window, { STRINGS, LocaleContext, LocaleProvider, useT, useLocale });
// Mock data — Ana + 3 dummy clients, foods, drinks, labs, psych

const ANA = {
  id: 'ana',
  firstName: 'Ana',
  lastName: 'Popescu',
  fullName: 'Ana Popescu',
  email: 'ana.popescu@example.com',
  sex: 'female',
  dob: '1991-03-12',
  age: 35,
  heightCm: 165,
  weightKg: 75,
  activity: 'moderate',
  activityFactor: 1.55,
  goal: 'lose_weight',
  wakeUp: '07:00',
  targetKcal: 1800,
  preferences: {
    vegan: false,
    vegetarian: true,
    lactoseIntolerant: false,
    glutenIntolerant: false,
    dislikesSpicy: true,
  },
  allergies: ['Nuci'],
  dislikedFoods: ['Broccoli', 'Vinete'],
  dislikedDrinks: ['Cafea'],
  fasting: { active: false, start: null, end: null },
  labResults: {
    date: '2026-04-15',
    items: [
      { key: 'vitamin_d', name: 'Vitamina D', value: 15, unit: 'ng/mL', refMin: 30, refMax: 100, status: 'outofrange', category: 'vitamins' },
      { key: 'hemoglobin', name: 'Hemoglobină', value: 13.2, unit: 'g/dL', refMin: 12, refMax: 16, status: 'normal', category: 'metabolic' },
      { key: 'tsh', name: 'TSH', value: 2.1, unit: 'mU/L', refMin: 0.4, refMax: 4.5, status: 'normal', category: 'hormonal' },
      { key: 'glucose', name: 'Glicemie à jeun', value: 92, unit: 'mg/dL', refMin: 70, refMax: 100, status: 'normal', category: 'metabolic' },
      { key: 'cholesterol', name: 'Colesterol total', value: 195, unit: 'mg/dL', refMin: 0, refMax: 200, status: 'normal', category: 'cardiac' },
    ],
  },
  psych: {
    date: '2026-04-15',
    totals: { anxiety: 10, stress: 7, sleep: 4, energy: 6, mood: 5 },
    // 0=never, 1=rar, 2=uneori, 3=des, 4=aproape mereu — three questions per category
    answers: {
      anxiety: [4, 3, 3],
      stress:  [3, 2, 2],
      sleep:   [2, 1, 1],
      energy:  [2, 2, 2],
      mood:    [2, 2, 1],
    },
    notes: "Pacientă raportează tensiune ridicată în ultimele 4 săptămâni, mai ales seara. Somn fragmentat 2–3 nopți pe săptămână.",
  },
  labValues: {
    alt: 28, ast: 24, ggt: 30, bilirubin: 0.8, alp: 78,
    creatinine: 0.85, urea: 28, uric_acid: 4.2, egfr: 95,
    cholesterol: 195, ldl: 118, hdl: 58, triglycerides: 95, hscrp: 1.2,
    glucose: 92, hba1c: 5.3, insulin: 8, hemoglobin: 13.2,
    tsh: 2.1, ft4: 1.1, cortisol: 14, estradiol: 165,
    vitamin_d: 15, vitamin_b12: 340, folate: 6.5, ferritin: 22, iron: 78,
  },
  subscription: {
    plan: 'standard',
    planName: 'Pachet Standard',
    totalMenus: 6,
    deliveredMenus: 2,
    priceRon: 1100,
    purchasedAt: '2026-04-20',
    cadenceDays: 14,
    endDate: '2026-07-13',
    status: 'active',
    nextDeliveryAt: '2026-05-18',
  },
  validations: {
    labTests: { lastUpdatedDate: '2026-04-15', nextRequiredUpdateDate: '2026-10-15', status: 'valid' },
    psychAssessment: { lastUpdatedDate: '2026-04-15', nextRequiredUpdateDate: '2026-10-15', status: 'valid' },
    allergies: { lastUpdatedDate: '2026-04-15', nextRequiredUpdateDate: '2027-04-15', status: 'valid' },
    preferences: { lastUpdatedDate: '2025-11-29', nextRequiredUpdateDate: '2026-05-29', status: 'pending_update' },
  },
  menus: [
    { id: 1, weekNumber: 1, startDate: '2026-04-22', status: 'delivered' },
    { id: 2, weekNumber: 2, startDate: '2026-05-06', status: 'delivered' },
  ],
};

const DUMMY_CLIENTS = [
  {
    id: 'mihai', firstName: 'Mihai', lastName: 'Ionescu', fullName: 'Mihai Ionescu',
    email: 'mihai.ionescu@example.com', sex: 'male', age: 42,
    plan: 'premium', planName: 'Pachet Premium', totalMenus: 12, deliveredMenus: 8,
    subscriptionStatus: 'active', validationStatus: 'valid',
    lastMenu: '2026-04-30', nextDelivery: '2026-05-14', remaining: 4,
  },
  {
    id: 'elena', firstName: 'Elena', lastName: 'Dumitrescu', fullName: 'Elena Dumitrescu',
    email: 'elena.dumitrescu@example.com', sex: 'female', age: 28,
    plan: 'starter', planName: 'Pachet Starter', totalMenus: 3, deliveredMenus: 1,
    subscriptionStatus: 'active', validationStatus: 'expired',
    lastMenu: '2026-04-08', nextDelivery: '2026-05-22', remaining: 2,
  },
  {
    id: 'radu', firstName: 'Radu', lastName: 'Stan', fullName: 'Radu Stan',
    email: 'radu.stan@example.com', sex: 'male', age: 51,
    plan: 'standard', planName: 'Pachet Standard', totalMenus: 6, deliveredMenus: 6,
    subscriptionStatus: 'completed', validationStatus: 'valid',
    lastMenu: '2026-04-25', nextDelivery: null, remaining: 0,
  },
];

const PLANS = [
  { key: 'starter', name: 'Pachet Starter', menus: 3, days: 42, priceRon: 600, popular: false,
    perks: ['Chestionar complet', '3 meniuri de 7 zile', 'Livrare prin email', 'Suport email'] },
  { key: 'standard', name: 'Pachet Standard', menus: 6, days: 84, priceRon: 1100, popular: true,
    perks: ['Tot din Starter', '6 meniuri de 7 zile', 'Reactualizare preferințe', 'Suport prioritar'] },
  { key: 'premium', name: 'Pachet Premium', menus: 12, days: 168, priceRon: 2000, popular: false,
    perks: ['Tot din Standard', '12 meniuri de 7 zile', 'Sesiune cu nutriționist', 'Listă cumpărături'] },
];

// Allergies master list
const ALLERGIES = ['Nuci', 'Arahide', 'Lactate', 'Gluten', 'Ouă', 'Pește', 'Crustacee', 'Soia', 'Susan', 'Muștar', 'Țelină', 'Lupin', 'Sulfiți'];

// Foods grouped by category
const FOODS = {
  fruits: ['Mere', 'Banane', 'Portocale', 'Mure', 'Căpșuni', 'Pere', 'Avocado', 'Kiwi'],
  vegetables: ['Morcovi', 'Spanac', 'Broccoli', 'Vinete', 'Roșii', 'Castraveți', 'Ardei', 'Dovlecei'],
  beef: ['Mușchi de vită', 'Antricot vită', 'Tartar de vită', 'Vită tocată', 'Coadă de vită', 'Ficat de vită'],
  pork: ['Cotlet porc', 'Pulpă porc', 'Mușchi porc', 'Costiță porc', 'Ceafă porc', 'Carne porc tocată'],
  poultry: ['Piept pui', 'Pulpe pui', 'Curcan piept', 'Curcan pulpă', 'Aripi pui', 'Rață'],
  fish: ['Somon', 'Macrou', 'Hering', 'Ton', 'Cod', 'Păstrăv', 'Sardine', 'Dorada'],
  dairy: ['Iaurt grecesc', 'Brânză feta', 'Cașcaval', 'Lapte', 'Mozzarella', 'Smântână', 'Telemea', 'Urdă'],
  cereals: ['Ovăz', 'Quinoa', 'Orez brun', 'Orez alb', 'Hrișcă', 'Mei', 'Bulgur', 'Paste integrale'],
  nuts_and_seeds: ['Migdale', 'Nuci', 'Caju', 'Semințe floarea-soarelui', 'Semințe dovleac', 'Chia', 'In', 'Susan'],
  snacks: ['Ciocolată neagră 70%', 'Batoane musli', 'Fructe uscate', 'Popcorn', 'Halva', 'Stafide'],
  soup: ['Supă cremă de dovleac', 'Supă de legume', 'Ciorbă de fasole', 'Supă miso', 'Borș de sfeclă'],
  eggs: ['Ouă fierte', 'Omletă', 'Ouă ochiuri', 'Ouă scrambled'],
};

// Drinks grouped by category
const DRINKS = {
  tea: ['Ceai verde', 'Ceai negru', 'Ceai de mușețel', 'Ceai de mentă', 'Ceai rooibos', 'Ceai de ghimbir'],
  coffee: ['Cafea espresso', 'Cafea filtru', 'Cappuccino', 'Cafea cu lapte vegetal'],
  alcohol: ['Vin roșu', 'Vin alb', 'Bere', 'Prosecco'],
  natural_juice: ['Suc de portocale', 'Suc de mere', 'Suc de morcovi', 'Suc de sfeclă'],
  water: ['Apă plată', 'Apă minerală', 'Apă cu lămâie'],
  smoothie: ['Smoothie verde', 'Smoothie de fructe de pădure', 'Smoothie banană-spanac'],
};

// Lab tests by category (~4-8 each)
const LAB_TESTS = {
  hepatic: [
    { key: 'alt', name: 'ALT (TGP)', unit: 'U/L', refMin: 0, refMax: 35 },
    { key: 'ast', name: 'AST (TGO)', unit: 'U/L', refMin: 0, refMax: 35 },
    { key: 'ggt', name: 'GGT', unit: 'U/L', refMin: 0, refMax: 38 },
    { key: 'bilirubin', name: 'Bilirubina totală', unit: 'mg/dL', refMin: 0.1, refMax: 1.2 },
    { key: 'alp', name: 'Fosfatază alcalină', unit: 'U/L', refMin: 35, refMax: 105 },
  ],
  renal: [
    { key: 'creatinine', name: 'Creatinină', unit: 'mg/dL', refMin: 0.5, refMax: 1.1 },
    { key: 'urea', name: 'Uree', unit: 'mg/dL', refMin: 17, refMax: 43 },
    { key: 'uric_acid', name: 'Acid uric', unit: 'mg/dL', refMin: 2.6, refMax: 6.0 },
    { key: 'egfr', name: 'eGFR', unit: 'mL/min', refMin: 60, refMax: 120 },
  ],
  tumor: [
    { key: 'cea', name: 'CEA', unit: 'ng/mL', refMin: 0, refMax: 5 },
    { key: 'ca125', name: 'CA 125', unit: 'U/mL', refMin: 0, refMax: 35 },
    { key: 'afp', name: 'AFP', unit: 'ng/mL', refMin: 0, refMax: 8 },
  ],
  cardiac: [
    { key: 'cholesterol', name: 'Colesterol total', unit: 'mg/dL', refMin: 0, refMax: 200 },
    { key: 'ldl', name: 'LDL', unit: 'mg/dL', refMin: 0, refMax: 130 },
    { key: 'hdl', name: 'HDL', unit: 'mg/dL', refMin: 40, refMax: 100 },
    { key: 'triglycerides', name: 'Trigliceride', unit: 'mg/dL', refMin: 0, refMax: 150 },
    { key: 'hscrp', name: 'hs-CRP', unit: 'mg/L', refMin: 0, refMax: 3 },
  ],
  metabolic: [
    { key: 'glucose', name: 'Glicemie à jeun', unit: 'mg/dL', refMin: 70, refMax: 100 },
    { key: 'hba1c', name: 'HbA1c', unit: '%', refMin: 4, refMax: 5.6 },
    { key: 'insulin', name: 'Insulină', unit: 'µU/mL', refMin: 2, refMax: 25 },
    { key: 'hemoglobin', name: 'Hemoglobină', unit: 'g/dL', refMin: 12, refMax: 16 },
  ],
  hormonal: [
    { key: 'tsh', name: 'TSH', unit: 'mU/L', refMin: 0.4, refMax: 4.5 },
    { key: 'ft4', name: 'FT4', unit: 'ng/dL', refMin: 0.8, refMax: 1.8 },
    { key: 'cortisol', name: 'Cortizol', unit: 'µg/dL', refMin: 5, refMax: 23 },
    { key: 'estradiol', name: 'Estradiol', unit: 'pg/mL', refMin: 30, refMax: 400 },
  ],
  vitamins: [
    { key: 'vitamin_d', name: 'Vitamina D (25-OH)', unit: 'ng/mL', refMin: 30, refMax: 100 },
    { key: 'vitamin_b12', name: 'Vitamina B12', unit: 'pg/mL', refMin: 200, refMax: 900 },
    { key: 'folate', name: 'Acid folic', unit: 'ng/mL', refMin: 3, refMax: 17 },
    { key: 'ferritin', name: 'Feritină', unit: 'ng/mL', refMin: 15, refMax: 150 },
    { key: 'iron', name: 'Fier seric', unit: 'µg/dL', refMin: 50, refMax: 170 },
  ],
};

// Psych questionnaire — 5 categories x 3 questions
const PSYCH_QUESTIONS = {
  anxiety: [
    "Te-ai simțit nervos sau tensionat?",
    "Ai avut dificultăți să te oprești din îngrijorat?",
    "Te-ai îngrijorat prea mult de lucruri diferite?",
  ],
  stress: [
    "Te-ai simțit copleșit de responsabilități?",
    "Ai avut senzația că nu poți face față cerințelor?",
    "Ai simțit tensiune fizică (umeri, mandibulă)?",
  ],
  sleep: [
    "Ai avut dificultăți să adormi?",
    "Te-ai trezit obosit dimineața?",
    "Te-ai trezit în timpul nopții?",
  ],
  energy: [
    "Te-ai simțit fără energie pentru activitățile zilnice?",
    "Ai simțit oboseală fizică pe parcursul zilei?",
    "Ai avut nevoie de cofeină pentru a funcționa?",
  ],
  mood: [
    "Te-ai simțit trist sau abătut?",
    "Ai avut puțin interes pentru activități plăcute?",
    "Te-ai simțit deconectat de cei din jur?",
  ],
};

// Day 1 menu — verbatim from spec
const DAY1_MEALS = [
  { mealType: 'breakfast', time: '07:00', kcal: 450, items: [
    { food: '2 ouă fierte', amount: '120g', kcal: 155, ruleSource: 'lab' },
    { food: 'Ovăz cu lapte vegetal', amount: '60g + 200ml', kcal: 220, ruleSource: 'default' },
    { food: '1 banană', amount: '120g', kcal: 105, ruleSource: 'psych' },
    { food: 'Ceai verde', amount: '200ml', kcal: 0, ruleSource: 'preference' },
  ]},
  { mealType: 'snack_1', time: '09:00', kcal: 180, items: [
    { food: 'Iaurt grecesc', amount: '150g', kcal: 130, ruleSource: 'default' },
    { food: 'Ciocolată neagră 70%', amount: '20g', kcal: 50, ruleSource: 'psych' },
  ]},
  { mealType: 'lunch', time: '11:00', kcal: 600, items: [
    { food: 'Orez brun cu ciuperci', amount: '180g', kcal: 280, ruleSource: 'lab' },
    { food: 'Salată verde', amount: '100g', kcal: 30, ruleSource: 'default' },
    { food: 'Hummus cu legume crude', amount: '80g + 150g', kcal: 240, ruleSource: 'preference' },
    { food: 'Apă plată', amount: '300ml', kcal: 0, ruleSource: 'default' },
  ]},
  { mealType: 'snack_2', time: '14:00', kcal: 170, items: [
    { food: 'Măr', amount: '180g', kcal: 95, ruleSource: 'preference' },
    { food: 'Semințe de floarea-soarelui', amount: '15g', kcal: 75, ruleSource: 'default' },
  ]},
  { mealType: 'dinner', time: '17:00', kcal: 400, items: [
    { food: 'Quinoa cu legume la grătar', amount: '200g', kcal: 280, ruleSource: 'default' },
    { food: 'Supă cremă de dovleac', amount: '300ml', kcal: 110, ruleSource: 'default' },
    { food: 'Ceai de mușețel', amount: '200ml', kcal: 0, ruleSource: 'psych' },
  ]},
];

// Days 2-7: plausible Ana-compliant (vegetarian, no nuts/broccoli/vinete/coffee, ~1800 kcal, vit-D & calming foods)
const DAY2_MEALS = [
  { mealType: 'breakfast', time: '07:00', kcal: 440, items: [
    { food: 'Omletă cu spanac și brânză feta', amount: '2 ouă + 80g', kcal: 280, ruleSource: 'lab' },
    { food: 'Pâine integrală', amount: '50g', kcal: 130, ruleSource: 'default' },
    { food: 'Ceai de mentă', amount: '200ml', kcal: 0, ruleSource: 'psych' },
    { food: 'Căpșuni', amount: '100g', kcal: 30, ruleSource: 'preference' },
  ]},
  { mealType: 'snack_1', time: '09:30', kcal: 190, items: [
    { food: 'Smoothie banană-spanac', amount: '300ml', kcal: 190, ruleSource: 'psych' },
  ]},
  { mealType: 'lunch', time: '12:00', kcal: 590, items: [
    { food: 'Quinoa cu ciuperci portobello', amount: '220g', kcal: 320, ruleSource: 'lab' },
    { food: 'Salată cu roșii și mozzarella', amount: '180g', kcal: 220, ruleSource: 'default' },
    { food: 'Apă cu lămâie', amount: '300ml', kcal: 5, ruleSource: 'default' },
    { food: 'Telemea proaspătă', amount: '15g', kcal: 45, ruleSource: 'preference' },
  ]},
  { mealType: 'snack_2', time: '15:00', kcal: 180, items: [
    { food: 'Iaurt grecesc cu miere', amount: '150g + 10g', kcal: 180, ruleSource: 'default' },
  ]},
  { mealType: 'dinner', time: '18:00', kcal: 400, items: [
    { food: 'Hrișcă cu legume coapte', amount: '200g', kcal: 290, ruleSource: 'default' },
    { food: 'Supă de legume', amount: '300ml', kcal: 110, ruleSource: 'default' },
    { food: 'Ceai rooibos', amount: '200ml', kcal: 0, ruleSource: 'psych' },
  ]},
];

const DAY3_MEALS = [
  { mealType: 'breakfast', time: '07:00', kcal: 460, items: [
    { food: 'Iaurt grecesc cu ovăz și fructe de pădure', amount: '180g + 40g + 100g', kcal: 360, ruleSource: 'preference' },
    { food: 'Semințe de chia', amount: '10g', kcal: 50, ruleSource: 'default' },
    { food: 'Ceai verde', amount: '200ml', kcal: 0, ruleSource: 'preference' },
    { food: 'Banană', amount: '50g', kcal: 50, ruleSource: 'psych' },
  ]},
  { mealType: 'snack_1', time: '09:30', kcal: 175, items: [
    { food: 'Hummus cu morcovi', amount: '60g + 100g', kcal: 175, ruleSource: 'preference' },
  ]},
  { mealType: 'lunch', time: '12:00', kcal: 600, items: [
    { food: 'Orez brun cu năut și roșii', amount: '220g', kcal: 380, ruleSource: 'lab' },
    { food: 'Salată cu castraveți și ardei', amount: '150g', kcal: 60, ruleSource: 'default' },
    { food: 'Brânză feta', amount: '40g', kcal: 110, ruleSource: 'default' },
    { food: 'Apă plată', amount: '300ml', kcal: 0, ruleSource: 'default' },
  ]},
  { mealType: 'snack_2', time: '15:30', kcal: 165, items: [
    { food: 'Ciocolată neagră 70%', amount: '25g', kcal: 130, ruleSource: 'psych' },
    { food: 'Ceai de mușețel', amount: '200ml', kcal: 0, ruleSource: 'psych' },
    { food: 'Stafide', amount: '10g', kcal: 35, ruleSource: 'default' },
  ]},
  { mealType: 'dinner', time: '18:00', kcal: 400, items: [
    { food: 'Paste integrale cu spanac și ciuperci', amount: '200g', kcal: 320, ruleSource: 'lab' },
    { food: 'Supă miso', amount: '250ml', kcal: 80, ruleSource: 'default' },
  ]},
];

const DAY4_MEALS = [
  { mealType: 'breakfast', time: '07:00', kcal: 450, items: [
    { food: 'Pâine integrală cu avocado și ouă ochiuri', amount: '50g + 80g + 2 ouă', kcal: 410, ruleSource: 'lab' },
    { food: 'Roșii cherry', amount: '60g', kcal: 15, ruleSource: 'default' },
    { food: 'Ceai de mentă', amount: '200ml', kcal: 0, ruleSource: 'psych' },
    { food: 'Pere', amount: '80g', kcal: 25, ruleSource: 'preference' },
  ]},
  { mealType: 'snack_1', time: '09:30', kcal: 180, items: [
    { food: 'Smoothie verde (spanac, măr, banană)', amount: '300ml', kcal: 180, ruleSource: 'psych' },
  ]},
  { mealType: 'lunch', time: '12:00', kcal: 600, items: [
    { food: 'Bulgur cu legume mediteraneene', amount: '220g', kcal: 320, ruleSource: 'default' },
    { food: 'Brânză halloumi la grătar', amount: '60g', kcal: 180, ruleSource: 'preference' },
    { food: 'Salată verde cu roșii', amount: '120g', kcal: 40, ruleSource: 'default' },
    { food: 'Suc natural de morcovi', amount: '200ml', kcal: 60, ruleSource: 'default' },
  ]},
  { mealType: 'snack_2', time: '15:30', kcal: 170, items: [
    { food: 'Iaurt grecesc cu miere', amount: '120g', kcal: 130, ruleSource: 'default' },
    { food: 'Semințe de dovleac', amount: '8g', kcal: 40, ruleSource: 'default' },
  ]},
  { mealType: 'dinner', time: '18:00', kcal: 400, items: [
    { food: 'Quinoa cu ciuperci și caise', amount: '200g', kcal: 290, ruleSource: 'lab' },
    { food: 'Ciorbă de fasole albă', amount: '300ml', kcal: 110, ruleSource: 'default' },
    { food: 'Ceai rooibos', amount: '200ml', kcal: 0, ruleSource: 'psych' },
  ]},
];

const DAY5_MEALS = [
  { mealType: 'breakfast', time: '07:00', kcal: 450, items: [
    { food: 'Ovăz cu lapte și mere', amount: '60g + 200ml + 100g', kcal: 320, ruleSource: 'default' },
    { food: 'Semințe de in', amount: '10g', kcal: 55, ruleSource: 'default' },
    { food: '2 ouă fierte', amount: '120g', kcal: 75, ruleSource: 'lab' },
    { food: 'Ceai verde', amount: '200ml', kcal: 0, ruleSource: 'preference' },
  ]},
  { mealType: 'snack_1', time: '09:30', kcal: 180, items: [
    { food: 'Iaurt grecesc cu căpșuni', amount: '150g + 80g', kcal: 180, ruleSource: 'preference' },
  ]},
  { mealType: 'lunch', time: '12:00', kcal: 600, items: [
    { food: 'Risotto cu ciuperci portobello', amount: '230g', kcal: 380, ruleSource: 'lab' },
    { food: 'Salată cu rucola și parmezan', amount: '120g', kcal: 160, ruleSource: 'default' },
    { food: 'Apă cu lămâie', amount: '300ml', kcal: 5, ruleSource: 'default' },
    { food: 'Pere', amount: '80g', kcal: 55, ruleSource: 'preference' },
  ]},
  { mealType: 'snack_2', time: '15:30', kcal: 170, items: [
    { food: 'Banană', amount: '120g', kcal: 105, ruleSource: 'psych' },
    { food: 'Ciocolată neagră 70%', amount: '12g', kcal: 65, ruleSource: 'psych' },
  ]},
  { mealType: 'dinner', time: '18:00', kcal: 400, items: [
    { food: 'Hrișcă cu spanac și brânză feta', amount: '200g', kcal: 310, ruleSource: 'default' },
    { food: 'Supă cremă de dovleac', amount: '250ml', kcal: 90, ruleSource: 'default' },
    { food: 'Ceai de mușețel', amount: '200ml', kcal: 0, ruleSource: 'psych' },
  ]},
];

const DAY6_MEALS = [
  { mealType: 'breakfast', time: '07:30', kcal: 470, items: [
    { food: 'Clătite din ovăz cu fructe de pădure', amount: '2 buc + 100g', kcal: 350, ruleSource: 'preference' },
    { food: 'Iaurt grecesc', amount: '80g', kcal: 70, ruleSource: 'default' },
    { food: 'Ceai verde', amount: '200ml', kcal: 0, ruleSource: 'preference' },
    { food: 'Mere', amount: '120g', kcal: 50, ruleSource: 'preference' },
  ]},
  { mealType: 'snack_1', time: '10:00', kcal: 180, items: [
    { food: 'Smoothie de fructe de pădure', amount: '300ml', kcal: 180, ruleSource: 'preference' },
  ]},
  { mealType: 'lunch', time: '12:30', kcal: 600, items: [
    { food: 'Mei cu legume de toamnă coapte', amount: '220g', kcal: 320, ruleSource: 'default' },
    { food: 'Tofu marinat la grătar', amount: '120g', kcal: 200, ruleSource: 'preference' },
    { food: 'Salată de varză cu mărar', amount: '100g', kcal: 50, ruleSource: 'default' },
    { food: 'Apă plată', amount: '300ml', kcal: 0, ruleSource: 'default' },
  ]},
  { mealType: 'snack_2', time: '15:30', kcal: 150, items: [
    { food: 'Hummus cu castraveți', amount: '50g + 100g', kcal: 150, ruleSource: 'default' },
  ]},
  { mealType: 'dinner', time: '18:30', kcal: 400, items: [
    { food: 'Paste integrale cu pesto și ciuperci', amount: '200g', kcal: 310, ruleSource: 'lab' },
    { food: 'Supă de roșii cu busuioc', amount: '250ml', kcal: 90, ruleSource: 'default' },
    { food: 'Ceai rooibos', amount: '200ml', kcal: 0, ruleSource: 'psych' },
  ]},
];

const DAY7_MEALS = [
  { mealType: 'breakfast', time: '07:30', kcal: 460, items: [
    { food: 'Ovăz cu lapte și banană', amount: '60g + 200ml + 80g', kcal: 320, ruleSource: 'psych' },
    { food: 'Migdale', amount: '15g', kcal: 90, ruleSource: 'default' },
    { food: 'Iaurt grecesc', amount: '60g', kcal: 50, ruleSource: 'default' },
    { food: 'Ceai de mentă', amount: '200ml', kcal: 0, ruleSource: 'psych' },
  ]},
  { mealType: 'snack_1', time: '10:00', kcal: 180, items: [
    { food: 'Iaurt grecesc cu mure', amount: '150g + 80g', kcal: 180, ruleSource: 'preference' },
  ]},
  { mealType: 'lunch', time: '13:00', kcal: 600, items: [
    { food: 'Quinoa cu năut și legume', amount: '230g', kcal: 380, ruleSource: 'lab' },
    { food: 'Salată cu portocale și rucola', amount: '150g', kcal: 90, ruleSource: 'default' },
    { food: 'Brânză feta', amount: '40g', kcal: 110, ruleSource: 'default' },
    { food: 'Apă plată', amount: '300ml', kcal: 0, ruleSource: 'default' },
  ]},
  { mealType: 'snack_2', time: '16:00', kcal: 160, items: [
    { food: 'Mere coapte cu scorțișoară', amount: '180g', kcal: 100, ruleSource: 'preference' },
    { food: 'Ciocolată neagră 70%', amount: '12g', kcal: 60, ruleSource: 'psych' },
  ]},
  { mealType: 'dinner', time: '18:30', kcal: 400, items: [
    { food: 'Tocăniță de ciuperci cu polenta', amount: '230g', kcal: 310, ruleSource: 'lab' },
    { food: 'Supă cremă de dovleac', amount: '250ml', kcal: 90, ruleSource: 'default' },
    { food: 'Ceai de mușețel', amount: '200ml', kcal: 0, ruleSource: 'psych' },
  ]},
];

const ANA_WEEK = [DAY1_MEALS, DAY2_MEALS, DAY3_MEALS, DAY4_MEALS, DAY5_MEALS, DAY6_MEALS, DAY7_MEALS];

const FOOD_FREQUENCY = [
  { food: 'Ouă', last: '2026-04-30', last30: 12, total: 28 },
  { food: 'Iaurt grecesc', last: '2026-05-04', last30: 14, total: 36 },
  { food: 'Ovăz', last: '2026-05-04', last30: 10, total: 22 },
  { food: 'Quinoa', last: '2026-05-03', last30: 6, total: 14 },
  { food: 'Banană', last: '2026-05-04', last30: 8, total: 20 },
  { food: 'Ciocolată neagră 70%', last: '2026-05-03', last30: 7, total: 18 },
  { food: 'Brânză feta', last: '2026-05-02', last30: 5, total: 12 },
  { food: 'Hummus', last: '2026-05-01', last30: 5, total: 11 },
  { food: 'Spanac', last: '2026-05-04', last30: 7, total: 16 },
  { food: 'Ciuperci', last: '2026-05-04', last30: 8, total: 19 },
];

const DRINK_FREQUENCY = [
  { food: 'Ceai verde', last: '2026-05-04', last30: 18, total: 42 },
  { food: 'Apă plată', last: '2026-05-04', last30: 30, total: 84 },
  { food: 'Ceai de mușețel', last: '2026-05-04', last30: 9, total: 21 },
  { food: 'Smoothie verde', last: '2026-05-02', last30: 6, total: 14 },
  { food: 'Ceai de mentă', last: '2026-05-03', last30: 7, total: 16 },
];

// Subscriptions / payments table — Ana + dummy clients
const PAYMENTS = [
  { id: 'p1', clientName: 'Ana Popescu', plan: 'Pachet Standard', start: '2026-04-20', end: '2026-07-13', amount: 1100, status: 'active', paymentStatus: 'paid' },
  { id: 'p2', clientName: 'Mihai Ionescu', plan: 'Pachet Premium', start: '2026-02-10', end: '2026-07-28', amount: 2000, status: 'active', paymentStatus: 'paid' },
  { id: 'p3', clientName: 'Elena Dumitrescu', plan: 'Pachet Starter', start: '2026-04-01', end: '2026-05-13', amount: 600, status: 'active', paymentStatus: 'paid' },
  { id: 'p4', clientName: 'Radu Stan', plan: 'Pachet Standard', start: '2026-01-12', end: '2026-04-05', amount: 1100, status: 'completed', paymentStatus: 'paid' },
  { id: 'p5', clientName: 'Mihai Ionescu', plan: 'Pachet Standard', start: '2025-08-01', end: '2025-10-24', amount: 1100, status: 'completed', paymentStatus: 'paid' },
];

// Upcoming deliveries
const UPCOMING_DELIVERIES = [
  { date: '2026-05-09', client: 'Mihai Ionescu', plan: 'Premium', status: 'scheduled' },
  { date: '2026-05-13', client: 'Elena Dumitrescu', plan: 'Starter', status: 'generated' },
  { date: '2026-05-14', client: 'Mihai Ionescu', plan: 'Premium', status: 'scheduled' },
  { date: '2026-05-18', client: 'Ana Popescu', plan: 'Standard', status: 'scheduled' },
  { date: '2026-05-22', client: 'Elena Dumitrescu', plan: 'Starter', status: 'scheduled' },
];

const CATEGORY_LABELS = {
  fruits: { ro: 'Fructe', en: 'Fruits' },
  vegetables: { ro: 'Legume', en: 'Vegetables' },
  beef: { ro: 'Vită', en: 'Beef' },
  pork: { ro: 'Porc', en: 'Pork' },
  poultry: { ro: 'Pasăre', en: 'Poultry' },
  fish: { ro: 'Pește', en: 'Fish' },
  dairy: { ro: 'Lactate', en: 'Dairy' },
  cereals: { ro: 'Cereale', en: 'Cereals' },
  nuts_and_seeds: { ro: 'Nuci și semințe', en: 'Nuts & seeds' },
  snacks: { ro: 'Gustări', en: 'Snacks' },
  soup: { ro: 'Supe', en: 'Soups' },
  eggs: { ro: 'Ouă', en: 'Eggs' },
  tea: { ro: 'Ceaiuri', en: 'Teas' },
  coffee: { ro: 'Cafea', en: 'Coffee' },
  alcohol: { ro: 'Alcool', en: 'Alcohol' },
  natural_juice: { ro: 'Sucuri naturale', en: 'Natural juices' },
  water: { ro: 'Apă', en: 'Water' },
  smoothie: { ro: 'Smoothie', en: 'Smoothies' },
};

Object.assign(window, {
  ANA, DUMMY_CLIENTS, PLANS, ALLERGIES, FOODS, DRINKS, LAB_TESTS, PSYCH_QUESTIONS,
  ANA_WEEK, FOOD_FREQUENCY, DRINK_FREQUENCY, PAYMENTS, UPCOMING_DELIVERIES, CATEGORY_LABELS,
});
// Lightweight inline SVG icon set (lucide-style)
function Icon({ name, size = 18, className = '', strokeWidth = 1.8, ...rest }) {
  const paths = ICON_PATHS[name];
  if (!paths) return null;
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24"
      fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round"
      className={className} {...rest}>
      {paths}
    </svg>
  );
}

const ICON_PATHS = {
  check: <polyline points="20 6 9 17 4 12" />,
  x: <g><line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" /></g>,
  arrow_right: <g><line x1="5" y1="12" x2="19" y2="12" /><polyline points="12 5 19 12 12 19" /></g>,
  arrow_left: <g><line x1="19" y1="12" x2="5" y2="12" /><polyline points="12 19 5 12 12 5" /></g>,
  chevron_down: <polyline points="6 9 12 15 18 9" />,
  chevron_right: <polyline points="9 18 15 12 9 6" />,
  chevron_left: <polyline points="15 18 9 12 15 6" />,
  user: <g><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" /><circle cx="12" cy="7" r="4" /></g>,
  mail: <g><rect x="3" y="5" width="18" height="14" rx="2" /><polyline points="3 7 12 13 21 7" /></g>,
  lock: <g><rect x="4" y="11" width="16" height="10" rx="2" /><path d="M8 11V7a4 4 0 0 1 8 0v4" /></g>,
  bell: <g><path d="M18 8a6 6 0 1 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" /><path d="M13.7 21a2 2 0 0 1-3.4 0" /></g>,
  settings: <g><path d="M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></g>,
  log_out: <g><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" /><polyline points="16 17 21 12 16 7" /><line x1="21" y1="12" x2="9" y2="12" /></g>,
  log_in: <g><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4" /><polyline points="10 17 15 12 10 7" /><line x1="15" y1="12" x2="3" y2="12" /></g>,
  search: <g><circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" /></g>,
  download: <g><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="7 10 12 15 17 10" /><line x1="12" y1="15" x2="12" y2="3" /></g>,
  upload: <g><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="17 8 12 3 7 8" /><line x1="12" y1="3" x2="12" y2="15" /></g>,
  calendar: <g><rect x="3" y="4" width="18" height="18" rx="2" /><line x1="16" y1="2" x2="16" y2="6" /><line x1="8" y1="2" x2="8" y2="6" /><line x1="3" y1="10" x2="21" y2="10" /></g>,
  clock: <g><circle cx="12" cy="12" r="10" /><polyline points="12 6 12 12 16 14" /></g>,
  alert: <g><path d="M10.3 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" /><line x1="12" y1="9" x2="12" y2="13" /><line x1="12" y1="17" x2="12.01" y2="17" /></g>,
  info: <g><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></g>,
  leaf: <g><path d="M11 20A7 7 0 0 1 9.8 6.1C15.5 5 17 4.48 19 2c1 2 2 4.18 2 8 0 5.5-4.78 10-10 10z"/><path d="M2 21c0-3 1.85-5.36 5.08-6"/></g>,
  globe: <g><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></g>,
  menu: <g><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></g>,
  paperclip: <path d="M21.4 11 12.6 19.8a5 5 0 0 1-7-7l8.5-8.5a3.3 3.3 0 0 1 4.7 4.7L9.6 18.2a1.7 1.7 0 0 1-2.4-2.4l8-8" />,
  send: <g><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></g>,
  pause: <g><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></g>,
  play: <polygon points="5 3 19 12 5 21 5 3"/>,
  trash: <g><polyline points="3 6 5 6 21 6"/><path d="M19 6 17.7 20a2 2 0 0 1-2 1.8H8.3a2 2 0 0 1-2-1.8L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"/></g>,
  edit: <g><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.1 2.1 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></g>,
  plus: <g><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></g>,
  external: <g><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></g>,
  apple: <g><path d="M12 8c0-2 1-4 4-4 0 2-1 4-4 4z"/><path d="M19 13c0 6-3.5 9-7 9s-7-3-7-9 3.5-7 7-7 7 1 7 7z"/></g>,
  carrot: <g><path d="M5 21c-1-2 0-6 4-10s8-5 10-4c1 2 0 6-4 10s-8 5-10 4z"/><path d="M14 4c1 0 3 0 5-2"/><path d="M17 7c1 0 3 0 5-2"/><path d="M19 10c1 0 2 0 4-2"/></g>,
  bowl: <g><path d="M3 11h18a9 9 0 0 1-18 0z"/><path d="M12 4v3"/><path d="M9 6c0-1 1-2 3-2s3 1 3 2"/></g>,
  flame: <path d="M8.5 14.5A2.5 2.5 0 0 0 11 17c1.5 0 3-1 3-3 0-1-.5-2-1.5-2.5C13 11 13 9 12 8c-2 1-3 3-3 5 0 .5-.5 1-1 1.5z"/>,
  spark: <g><path d="M12 2v4"/><path d="M12 18v4"/><path d="M2 12h4"/><path d="M18 12h4"/><path d="m4.93 4.93 2.83 2.83"/><path d="m16.24 16.24 2.83 2.83"/><path d="m4.93 19.07 2.83-2.83"/><path d="m16.24 7.76 2.83-2.83"/></g>,
  filter: <polygon points="22 3 2 3 10 12.5 10 19 14 21 14 12.5 22 3"/>,
  more: <g><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/></g>,
  refresh: <g><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.5 9a9 9 0 0 1 14.85-3.36L23 10"/><path d="M20.5 15a9 9 0 0 1-14.85 3.36L1 14"/></g>,
  copy: <g><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></g>,
};

Object.assign(window, { Icon });
// Shared UI primitives — Button, Card, Pill, Input, Select, Switch, Tabs,
// Modal/Dialog, Toast, Progress, RadioGroup, Stepper, foodImageSlot

const cls = (...xs) => xs.filter(Boolean).join(' ');

function Button({ variant = 'primary', size, children, className = '', ...rest }) {
  const base = 'btn';
  const v = variant === 'primary' ? 'btn-primary'
    : variant === 'lime' ? 'btn-lime'
    : variant === 'outline' ? 'btn-outline'
    : variant === 'ghost' ? 'btn-ghost'
    : variant === 'coral' ? 'bg-coral text-white px-6 py-3 hover:bg-coral/90'
    : variant === 'dark' ? 'bg-ink text-white px-6 py-3 hover:bg-black'
    : 'btn-primary';
  return <button className={cls(base, v, size === 'sm' && 'btn-sm', className)} {...rest}>{children}</button>;
}

function Pill({ tone = 'neutral', children, className = '' }) {
  const tones = {
    neutral: 'bg-sage text-ink/70',
    green: 'bg-green-primary/10 text-green-dark',
    lime: 'bg-lime/20 text-olive',
    purple: 'bg-purple-primary/10 text-purple-primary',
    coral: 'bg-coral/15 text-coral',
    amber: 'bg-amber-100 text-amber-800',
    beige: 'bg-beige text-ink/80',
    blue: 'bg-blue-50 text-blue-700',
    paid: 'bg-green-primary/10 text-green-dark',
    pending: 'bg-amber-100 text-amber-800',
  };
  return <span className={cls('pill', tones[tone] || tones.neutral, className)}>{children}</span>;
}

function StatusPill({ status }) {
  const t = useT();
  const map = {
    valid:    { tone: 'green',  label: t('status_valid') },
    expired:  { tone: 'coral',  label: t('status_expired') },
    pending:  { tone: 'amber',  label: t('status_pending') },
    pending_update: { tone: 'amber', label: t('status_pending_update') },
    active:   { tone: 'green',  label: t('status_active') },
    completed:{ tone: 'neutral',label: t('status_completed') },
    cancelled:{ tone: 'coral',  label: t('status_cancelled') },
    paused:   { tone: 'amber',  label: t('status_paused') },
    paid:     { tone: 'green',  label: t('status_paid') },
    refunded: { tone: 'neutral',label: t('status_refunded') },
    scheduled:{ tone: 'blue',   label: t('status_scheduled') },
    generated:{ tone: 'green',  label: t('status_generated') },
    generating:{ tone: 'amber', label: t('status_generating') },
    normal:   { tone: 'green',  label: t('status_normal') },
    attention:{ tone: 'amber',  label: t('status_attention') },
    outofrange:{ tone: 'coral', label: t('status_outofrange') },
    delivered:{ tone: 'green',  label: 'Livrat' },
  };
  const d = map[status] || { tone: 'neutral', label: status };
  return <Pill tone={d.tone}>{d.label}</Pill>;
}

function RuleSourcePill({ source }) {
  const t = useT();
  const tones = { lab: 'purple', psych: 'amber', preference: 'lime', default: 'neutral' };
  const labels = { lab: t('rs_lab'), psych: t('rs_psych'), preference: t('rs_preference'), default: t('rs_default') };
  return <Pill tone={tones[source] || 'neutral'}>{labels[source] || source}</Pill>;
}

function Field({ label, hint, error, children, className = '' }) {
  return (
    <div className={className}>
      {label && <label className="label">{label}</label>}
      {children}
      {hint && !error && <div className="text-xs text-ink/55 mt-1.5">{hint}</div>}
      {error && <div className="text-xs text-coral mt-1.5">{error}</div>}
    </div>
  );
}

function Input({ className = '', ...rest }) {
  return <input className={cls('input', className)} {...rest} />;
}

function Textarea({ className = '', ...rest }) {
  return <textarea className={cls('input min-h-[100px] resize-y', className)} {...rest} />;
}

function Select({ options, value, onChange, className = '', children, ...rest }) {
  return (
    <div className={cls('relative', className)}>
      <select className="input pr-10 appearance-none cursor-pointer" value={value} onChange={onChange} {...rest}>
        {options ? options.map(o => <option key={o.value} value={o.value}>{o.label}</option>) : children}
      </select>
      <Icon name="chevron_down" className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none text-ink/55" size={16} />
    </div>
  );
}

function Switch({ checked, onChange, label, sublabel, disabled }) {
  return (
    <label className={cls("flex items-center gap-3 cursor-pointer select-none", disabled && 'opacity-60 cursor-not-allowed')}>
      <span
        onClick={() => !disabled && onChange(!checked)}
        className={cls(
          "relative inline-block w-11 h-6 rounded-full transition-colors flex-shrink-0",
          checked ? 'bg-green-primary' : 'bg-sage'
        )}
      >
        <span className={cls("absolute top-0.5 w-5 h-5 bg-white rounded-full shadow transition-all", checked ? 'left-[22px]' : 'left-0.5')} />
      </span>
      {(label || sublabel) && (
        <span className="leading-tight">
          {label && <span className="text-sm font-medium block text-ink">{label}</span>}
          {sublabel && <span className="text-xs text-ink/60 block">{sublabel}</span>}
        </span>
      )}
    </label>
  );
}

function RadioGroup({ value, onChange, options, name, layout = 'stack' }) {
  return (
    <div className={cls(layout === 'row' ? 'flex flex-wrap gap-2' : 'flex flex-col gap-2')}>
      {options.map(opt => {
        const selected = value === opt.value;
        return (
          <label key={opt.value}
            className={cls(
              "border rounded-2xl px-4 py-3 cursor-pointer flex items-start gap-3 transition-all",
              selected ? 'border-green-primary bg-green-primary/5' : 'border-sage hover:border-green-primary/40 bg-white',
              layout === 'row' && 'flex-1 min-w-[140px]'
            )}>
            <input type="radio" name={name} className="sr-only" checked={selected} onChange={() => onChange(opt.value)} />
            <span className={cls("inline-block w-4 h-4 rounded-full border-2 flex-shrink-0 mt-0.5",
              selected ? 'border-green-primary' : 'border-sage')}>
              {selected && <span className="block w-2 h-2 m-auto mt-[3px] rounded-full bg-green-primary" />}
            </span>
            <span className="leading-tight">
              <span className="text-sm font-medium block text-ink">{opt.label}</span>
              {opt.description && <span className="text-xs text-ink/60 block mt-0.5">{opt.description}</span>}
            </span>
          </label>
        );
      })}
    </div>
  );
}

function Checkbox({ checked, onChange, label, disabled }) {
  return (
    <label className={cls("inline-flex items-start gap-2.5 cursor-pointer", disabled && 'opacity-60 cursor-not-allowed')}>
      <span
        onClick={(e) => { if (!disabled) { e.preventDefault(); onChange(!checked); } }}
        className={cls("inline-flex items-center justify-center flex-shrink-0 w-5 h-5 rounded-md border-2 transition-colors mt-0.5",
          checked ? 'bg-green-primary border-green-primary' : 'bg-white border-sage')}>
        {checked && <Icon name="check" size={12} strokeWidth={3} className="text-white" />}
      </span>
      {label && <span className="text-sm text-ink/85 leading-snug">{label}</span>}
    </label>
  );
}

function Progress({ value, max = 100, className = '', tone = 'green' }) {
  const pct = Math.max(0, Math.min(100, (value / max) * 100));
  return (
    <div className={cls("w-full h-2 rounded-full bg-sage overflow-hidden", className)}>
      <div className={cls("h-full rounded-full transition-all",
        tone === 'green' ? 'bg-green-primary' : tone === 'lime' ? 'bg-lime' : 'bg-purple-primary')}
        style={{ width: `${pct}%` }} />
    </div>
  );
}

// ---- Modal (rendered via portal so nav can never overlap) ----
function Modal({ open, onClose, title, children, size = 'md', footer, contentClass = '' }) {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose && onClose(); };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
  }, [open, onClose]);
  if (!open) return null;
  const widths = { sm: 'max-w-md', md: 'max-w-lg', lg: 'max-w-2xl', xl: 'max-w-4xl' };
  const node = (
    <div className="fixed inset-0 z-[9999] fade-up" role="dialog" aria-modal="true">
      <div className="absolute inset-0 bg-ink/50 backdrop-blur-sm" onClick={onClose} />
      <div className="absolute inset-0 overflow-y-auto">
        <div className="min-h-full flex items-center justify-center p-4">
          <div className={cls("relative bg-white rounded-3xl shadow-card w-full flex flex-col my-8", widths[size])}>
            {title && (
              <div className="flex items-center justify-between px-6 py-4 border-b border-sage flex-shrink-0">
                <h3 className="h2 text-lg">{title}</h3>
                <button onClick={onClose} className="p-2 -mr-2 rounded-full hover:bg-sage transition-colors">
                  <Icon name="x" size={18} />
                </button>
              </div>
            )}
            <div className={cls("px-6 py-5", contentClass)}>{children}</div>
            {footer && <div className="px-6 py-4 border-t border-sage bg-cream/40 flex items-center justify-end gap-2 flex-shrink-0 rounded-b-3xl">{footer}</div>}
          </div>
        </div>
      </div>
    </div>
  );
  return ReactDOM.createPortal(node, document.body);
}

// ---- Toast ----
const ToastContext = React.createContext({ push: () => {} });
function ToastProvider({ children }) {
  const [items, setItems] = React.useState([]);
  const push = React.useCallback((msg, opts = {}) => {
    const id = Math.random().toString(36).slice(2);
    setItems(arr => [...arr, { id, msg, tone: opts.tone || 'success' }]);
    setTimeout(() => setItems(arr => arr.filter(x => x.id !== id)), opts.duration || 3000);
  }, []);
  return (
    <ToastContext.Provider value={{ push }}>
      {children}
      <div className="fixed top-4 right-4 z-[200] flex flex-col gap-2 pointer-events-none">
        {items.map(it => (
          <div key={it.id} className={cls("fade-up pointer-events-auto rounded-2xl shadow-card px-4 py-3 text-sm font-medium flex items-center gap-2",
            it.tone === 'success' ? 'bg-green-primary text-white' :
            it.tone === 'coral' ? 'bg-coral text-white' :
            'bg-white text-ink')}>
            {it.tone === 'success' && <Icon name="check" size={16} strokeWidth={2.4} />}
            {it.tone === 'coral' && <Icon name="alert" size={16} />}
            {it.msg}
          </div>
        ))}
      </div>
    </ToastContext.Provider>
  );
}
function useToast() { return React.useContext(ToastContext); }

// ---- Tabs ----
function Tabs({ value, onChange, options, dense = false, scroll = true }) {
  return (
    <div className={cls("flex gap-1 border-b border-sage", scroll ? 'overflow-x-auto' : 'flex-wrap')}>
      {options.map(o => {
        const active = value === o.value;
        return (
          <button key={o.value}
            onClick={() => onChange(o.value)}
            className={cls("relative px-4 py-2.5 text-sm font-medium whitespace-nowrap transition-colors",
              dense ? 'py-2 px-3' : '',
              active ? 'text-green-primary' : 'text-ink/55 hover:text-ink/80')}>
            {o.label}
            {o.badge && <span className="ml-1.5">{o.badge}</span>}
            {active && <span className="absolute left-2 right-2 -bottom-px h-0.5 bg-green-primary rounded-full" />}
          </button>
        );
      })}
    </div>
  );
}

// ---- Watercolor blob accents ----
function Blob({ color = '#95C500', x, y, size = 280, opacity = 0.18, className = '' }) {
  return (
    <svg
      width={size} height={size} viewBox="0 0 200 200"
      style={{ position: 'absolute', left: x, top: y, opacity, pointerEvents: 'none', filter: 'blur(8px)' }}
      className={className}
      aria-hidden>
      <path fill={color} d="M52.6 -55.3C66.4 -42.4 74.4 -21.2 73.5 -0.9C72.6 19.5 62.7 39 49 53.1C35.2 67.2 17.6 75.9 -1.4 77.3C-20.4 78.7 -40.7 72.8 -54.8 58.7C-68.8 44.6 -76.5 22.3 -75.1 1.4C-73.7 -19.5 -63.1 -39 -49 -52C-35 -64.9 -17.5 -71.4 1.9 -73.3C21.2 -75.2 38.7 -68.2 52.6 -55.3Z" transform="translate(100 100)" />
    </svg>
  );
}

// Watercolor splash for hero — multi-color
function HeroBlobs() {
  return (
    <div className="absolute inset-0 overflow-hidden pointer-events-none -z-10">
      <Blob color="#95C500" x="-80px" y="-40px" size={420} opacity={0.18} />
      <Blob color="#A874A8" x="auto" y="-60px" size={360} opacity={0.13} className="!right-[-60px] !left-auto" />
      <Blob color="#417A3E" x="auto" y="auto" size={420} opacity={0.10} className="!right-[15%] !bottom-[-120px] !top-auto !left-auto" />
    </div>
  );
}

// ---- Food image placeholder slot — uses inline SVG with food iconography ----
function FoodImage({ kind = 'plate', size = 'md', className = '' }) {
  const sizes = { sm: 'h-16 w-16', md: 'h-24 w-24', lg: 'h-40 w-full', xl: 'h-56 w-full' };
  const palettes = {
    plate: { bg: '#EFE3CA', shape: '#95C500' },
    bowl: { bg: '#EEF1E4', shape: '#417A3E' },
    fruit: { bg: '#FDF2E5', shape: '#E85C41' },
    grain: { bg: '#F4F6EE', shape: '#597600' },
    drink: { bg: '#EEF1E4', shape: '#A874A8' },
    leaf: { bg: '#EEF1E4', shape: '#417A3E' },
  };
  const p = palettes[kind] || palettes.plate;
  return (
    <div className={cls('relative rounded-2xl overflow-hidden flex items-center justify-center', sizes[size], className)}
      style={{ background: p.bg }}>
      <FoodIllustration kind={kind} color={p.shape} />
    </div>
  );
}

function FoodIllustration({ kind, color }) {
  // Slightly different organic SVG per kind, used as placeholder
  const common = { fill: 'none', stroke: color, strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round' };
  if (kind === 'bowl') return (
    <svg viewBox="0 0 64 64" width="60%" height="60%">
      <ellipse cx="32" cy="22" rx="16" ry="3.5" {...common} fill="#fff8" />
      <path d="M14 22 C14 38, 22 48, 32 48 C42 48, 50 38, 50 22" {...common} fill={color} fillOpacity="0.18" />
      <path d="M22 16 C24 12, 30 12, 32 16" {...common} />
      <circle cx="38" cy="20" r="2" fill={color} />
    </svg>
  );
  if (kind === 'fruit') return (
    <svg viewBox="0 0 64 64" width="60%" height="60%">
      <path d="M32 14 C20 14, 14 26, 18 38 C22 50, 30 54, 36 50 C44 54, 50 46, 50 36 C50 22, 44 14, 32 14Z" fill={color} fillOpacity="0.18" {...common} />
      <path d="M30 12 C32 8, 38 8, 40 14" {...common} />
      <path d="M22 26 C24 24, 26 24, 28 26" {...common} />
    </svg>
  );
  if (kind === 'grain') return (
    <svg viewBox="0 0 64 64" width="60%" height="60%">
      <path d="M32 12 L32 50" {...common} />
      <path d="M32 18 C26 16, 24 22, 28 24 M32 24 C26 22, 24 28, 28 30 M32 30 C26 28, 24 34, 28 36 M32 36 C26 34, 24 40, 28 42" {...common} />
      <path d="M32 18 C38 16, 40 22, 36 24 M32 24 C38 22, 40 28, 36 30 M32 30 C38 28, 40 34, 36 36 M32 36 C38 34, 40 40, 36 42" {...common} />
    </svg>
  );
  if (kind === 'drink') return (
    <svg viewBox="0 0 64 64" width="55%" height="65%">
      <path d="M22 14 L42 14 L40 50 L24 50 Z" fill={color} fillOpacity="0.18" {...common} />
      <path d="M22 22 L42 22" {...common} />
      <circle cx="32" cy="32" r="2" fill={color} />
      <path d="M28 8 C30 11, 32 11, 32 14" {...common} />
    </svg>
  );
  if (kind === 'leaf') return (
    <svg viewBox="0 0 64 64" width="60%" height="60%">
      <path d="M14 50 C14 30, 30 14, 50 14 C50 34, 34 50, 14 50Z" fill={color} fillOpacity="0.22" {...common} />
      <path d="M14 50 L40 24" {...common} />
      <path d="M22 38 L30 32 M28 44 L36 38" {...common} />
    </svg>
  );
  // plate (default)
  return (
    <svg viewBox="0 0 64 64" width="65%" height="65%">
      <circle cx="32" cy="32" r="22" fill="#fff8" stroke={color} strokeWidth="1.6" />
      <circle cx="32" cy="32" r="14" fill={color} fillOpacity="0.22" stroke={color} strokeWidth="1.4" />
      <circle cx="28" cy="28" r="3" fill={color} />
      <circle cx="36" cy="34" r="2.4" fill={color} fillOpacity="0.6" />
      <circle cx="30" cy="38" r="2" fill={color} fillOpacity="0.6" />
    </svg>
  );
}

// ---- Empty state ----
function EmptyState({ icon = 'leaf', title, sub, action }) {
  return (
    <div className="text-center py-10 px-6">
      <div className="mx-auto w-20 h-20 rounded-full bg-sage flex items-center justify-center mb-4">
        <Icon name={icon} size={28} className="text-green-primary" />
      </div>
      <div className="serif text-lg text-ink/85 mb-1">{title}</div>
      {sub && <div className="text-sm text-ink/55 max-w-sm mx-auto">{sub}</div>}
      {action && <div className="mt-4">{action}</div>}
    </div>
  );
}

// ---- Tooltip wrapper (CSS only) ----
function Tooltip({ label, text, children }) {
  const content = label ?? text;
  return (
    <span className="relative inline-flex group">
      {children}
      {content && (
        <span className="pointer-events-none absolute -top-2 left-1/2 -translate-x-1/2 -translate-y-full px-2.5 py-1.5 rounded-lg bg-ink text-white text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity z-50">
          {content}
        </span>
      )}
    </span>
  );
}

// ---- Section heading ----
function SectionHead({ eyebrow, title, sub, align = 'left' }) {
  return (
    <div className={cls(align === 'center' ? 'text-center' : '')}>
      {eyebrow && <div className="uppercase tracking-[0.16em] text-xs text-olive font-semibold mb-3">{eyebrow}</div>}
      <h2 className="h2 text-3xl md:text-4xl mb-2 leading-[1.1]">{title}</h2>
      {sub && <p className="text-ink/65 max-w-xl text-base md:text-[17px]" style={{ marginLeft: align === 'center' ? 'auto' : 0, marginRight: align === 'center' ? 'auto' : 0 }}>{sub}</p>}
    </div>
  );
}

function Avatar({ name = '', size = 36 }) {
  const initials = name.split(/\s+/).filter(Boolean).slice(0, 2).map(p => p[0]).join('').toUpperCase() || '?';
  const palette = ['#417A3E', '#662D91', '#597600', '#A874A8', '#95C500'];
  let hash = 0; for (let i = 0; i < name.length; i++) hash = (hash * 31 + name.charCodeAt(i)) | 0;
  const bg = palette[Math.abs(hash) % palette.length];
  const fontSize = Math.round(size * 0.4);
  return (
    <div className="rounded-full flex items-center justify-center text-white font-semibold flex-shrink-0"
      style={{ width: size, height: size, background: bg, fontSize }}>
      {initials}
    </div>
  );
}

Object.assign(window, {
  cls, Button, Pill, StatusPill, RuleSourcePill, Field, Input, Textarea, Select, Switch, RadioGroup, Checkbox, Progress,
  Modal, ToastProvider, ToastContext, useToast, Tabs, Blob, HeroBlobs, FoodImage, FoodIllustration,
  Avatar, Tooltip,
  EmptyState, Tooltip, SectionHead,
});
// App shell — routing, AppContext (auth, demoMode, subscription state), Nav, Footer, DemoSwitcher

// ---- Hash routing ----
function parseHash() {
  const h = window.location.hash || '#/';
  const [pathPart, queryPart] = h.slice(1).split('?');
  const path = pathPart || '/';
  const query = {};
  if (queryPart) {
    queryPart.split('&').forEach(kv => { const [k, v] = kv.split('='); query[decodeURIComponent(k)] = decodeURIComponent(v || ''); });
  }
  return { path, query };
}
function navigate(path) {
  if (path.startsWith('#')) path = path.slice(1);
  window.location.hash = path;
}

const RouterContext = React.createContext({ path: '/', query: {}, navigate });
function RouterProvider({ children }) {
  const [route, setRoute] = React.useState(parseHash());
  React.useEffect(() => {
    const handler = () => { setRoute(parseHash()); window.scrollTo(0, 0); };
    window.addEventListener('hashchange', handler);
    if (!window.location.hash) window.location.hash = '#/';
    return () => window.removeEventListener('hashchange', handler);
  }, []);
  return <RouterContext.Provider value={{ ...route, navigate }}>{children}</RouterContext.Provider>;
}
function useRouter() { return React.useContext(RouterContext); }

// Match `/admin/clients/:clientId` like patterns
function matchRoute(pattern, path) {
  const pp = pattern.split('/').filter(Boolean);
  const ap = path.split('/').filter(Boolean);
  if (pp.length !== ap.length) return null;
  const params = {};
  for (let i = 0; i < pp.length; i++) {
    if (pp[i].startsWith(':')) params[pp[i].slice(1)] = decodeURIComponent(ap[i]);
    else if (pp[i] !== ap[i]) return null;
  }
  return params;
}

// ---- App state context (demoMode, ana data with overrides, subscription state) ----
const AppContext = React.createContext(null);

const DEMO_MODES = ['visitor', 'fresh_purchase', 'first_menu', 'active', 'expired_labs', 'admin'];

function AppProvider({ children }) {
  const [demoMode, setDemoModeState] = React.useState(() => {
    try { return localStorage.getItem('app.demoMode') || 'visitor'; } catch (e) { return 'visitor'; }
  });
  const setDemoMode = React.useCallback((m) => {
    setDemoModeState(m);
    try { localStorage.setItem('app.demoMode', m); } catch (e) {}
  }, []);

  // Subscription override (for pause/cancel/reset demo)
  const [subOverride, setSubOverrideState] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('app.subOverride') || 'null'); } catch (e) { return null; }
  });
  const setSubOverride = React.useCallback((o) => {
    setSubOverrideState(o);
    try {
      if (o) localStorage.setItem('app.subOverride', JSON.stringify(o));
      else localStorage.removeItem('app.subOverride');
    } catch (e) {}
  }, []);

  // First-menu modal acceptance
  const [firstMenuAccepted, setFirstMenuAcceptedState] = React.useState(() => {
    try { return localStorage.getItem('account.firstMenuAccepted') === 'true'; } catch (e) { return false; }
  });
  const setFirstMenuAccepted = React.useCallback((v) => {
    setFirstMenuAcceptedState(v);
    try { localStorage.setItem('account.firstMenuAccepted', String(v)); } catch (e) {}
  }, []);

  // Compute Ana with overrides applied
  const ana = React.useMemo(() => {
    const a = JSON.parse(JSON.stringify(window.ANA));
    if (demoMode === 'expired_labs') {
      a.validations.labTests.status = 'expired';
      a.labResults.date = '2025-10-01';
    }
    if (demoMode === 'first_menu') {
      a.subscription.deliveredMenus = 0;
      a.menus = [];
    }
    if (demoMode === 'fresh_purchase') {
      // Just bought package — form not filled at all
      a.subscription.deliveredMenus = 0;
      a.menus = [];
      a.labResults = null;
      a.psych = null;
      a.preferences = {};
      a.allergies = [];
      a.dislikedFoods = [];
      a.dislikedDrinks = [];
      a.weightKg = null;
      a.targetKcal = null;
      a.activity = null;
      a.goal = null;
      a.formCompleted = false;
      a.validations = {
        labTests: { lastUpdatedDate: null, nextRequiredUpdateDate: null, status: 'not_started' },
        psychAssessment: { lastUpdatedDate: null, nextRequiredUpdateDate: null, status: 'not_started' },
        allergies: { lastUpdatedDate: null, nextRequiredUpdateDate: null, status: 'not_started' },
        preferences: { lastUpdatedDate: null, nextRequiredUpdateDate: null, status: 'not_started' },
      };
    }
    if (subOverride) {
      Object.assign(a.subscription, subOverride);
    }
    return a;
  }, [demoMode, subOverride]);

  const role = demoMode === 'admin' ? 'admin' : demoMode === 'visitor' ? 'visitor' : 'client';

  return (
    <AppContext.Provider value={{
      demoMode, setDemoMode, role, ana,
      subOverride, setSubOverride,
      firstMenuAccepted, setFirstMenuAccepted,
    }}>
      {children}
    </AppContext.Provider>
  );
}
function useApp() { return React.useContext(AppContext); }

// ---- Logo (uses uploaded PNG) ----
function Logo({ size = 'md', className = '' }) {
  const heights = { sm: 'h-8', md: 'h-10', lg: 'h-14', xl: 'h-20' };
  return (
    <a href="#/" className={cls("inline-flex items-center gap-2", className)} onClick={(e) => { e.preventDefault(); navigate('/'); }}>
      <img src="assets/logo.png" alt="Silueta Naturală" className={cls(heights[size], 'w-auto')} />
    </a>
  );
}

// ---- Locale toggle (segmented) ----
function LocaleToggle({ size = 'sm' }) {
  const { locale, setLocale } = useLocale();
  return (
    <div className={cls("inline-flex items-center bg-sage rounded-full p-0.5",
      size === 'sm' ? 'text-xs' : 'text-sm')}>
      {['ro', 'en'].map(l => (
        <button key={l} onClick={() => setLocale(l)}
          className={cls("px-2.5 py-1 rounded-full font-semibold transition-colors uppercase",
            locale === l ? 'bg-white text-green-primary shadow-sm' : 'text-ink/60 hover:text-ink/80')}>
          {l}
        </button>
      ))}
    </div>
  );
}

// ---- Top Nav ----
function Nav() {
  const t = useT();
  const { path } = useRouter();
  const { role, demoMode, setDemoMode } = useApp();
  const [mobileOpen, setMobileOpen] = React.useState(false);

  // Hide nav for full-screen flows? We always show but compose links by role.
  const links = role === 'admin' ? [
    { path: '/admin', label: t('nav_admin_dashboard') },
    { path: '/admin/clients', label: t('nav_admin_clients') },
    { path: '/admin/menus', label: t('nav_admin_menus') },
    { path: '/admin/subscriptions', label: t('nav_admin_subs') },
  ] : role === 'client' ? [
    { path: '/account', label: t('nav_dashboard') },
    { path: '/account/settings', label: t('nav_settings') },
  ] : [
    { path: '/plans', label: t('nav_plans') },
    { path: '/#how', label: t('nav_how'), hashTarget: 'how' },
    { path: '/#faq', label: t('nav_faq'), hashTarget: 'faq' },
  ];

  const onLogout = () => {
    setDemoMode('visitor');
    navigate('/');
  };

  return (
    <header className="sticky top-0 z-40 bg-cream/85 backdrop-blur-md border-b border-sage/70">
      <div className="max-w-7xl mx-auto px-4 md:px-8 h-20 flex items-center justify-between gap-4">
        <div className="flex items-center gap-8">
          <Logo size="lg" />
          <nav className="hidden md:flex items-center gap-1">
            {links.map(l => {
              const active = !l.hashTarget && (path === l.path || (l.path !== '/' && path.startsWith(l.path)));
              return (
                <a key={l.path} href={`#${l.path}`}
                  onClick={(e) => {
                    e.preventDefault();
                    if (l.hashTarget) {
                      navigate('/');
                      setTimeout(() => {
                        const el = document.getElementById(l.hashTarget);
                        if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
                      }, 50);
                    } else navigate(l.path);
                  }}
                  className={cls("px-3 py-2 rounded-full text-sm font-medium transition-colors",
                    active ? 'text-green-primary bg-green-primary/10' : 'text-ink/70 hover:text-ink hover:bg-sage')}>
                  {l.label}
                </a>
              );
            })}
          </nav>
        </div>

        <div className="flex items-center gap-2">
          <LocaleToggle />
          {role === 'visitor' ? (
            <Button variant="outline" size="sm" onClick={() => navigate('/login')} className="hidden sm:inline-flex">
              <Icon name="log_in" size={15} />
              {t('nav_login')}
            </Button>
          ) : (
            <button onClick={onLogout} className="hidden sm:inline-flex items-center gap-1.5 px-3 py-2 rounded-full text-sm font-medium text-ink/65 hover:text-ink hover:bg-sage transition-colors">
              <Icon name="log_out" size={15} />
              <span>{t('nav_logout')}</span>
            </button>
          )}
          <button className="md:hidden p-2 rounded-full hover:bg-sage" onClick={() => setMobileOpen(o => !o)}>
            <Icon name="menu" size={20} />
          </button>
        </div>
      </div>

      {mobileOpen && (
        <div className="md:hidden border-t border-sage bg-white px-4 py-3 flex flex-col gap-1">
          {links.map(l => (
            <a key={l.path} href={`#${l.path}`}
              onClick={(e) => { e.preventDefault(); navigate(l.path); setMobileOpen(false); }}
              className="px-3 py-2.5 rounded-xl text-sm font-medium text-ink/80 hover:bg-sage">
              {l.label}
            </a>
          ))}
          {role === 'visitor' && (
            <button className="text-left px-3 py-2.5 rounded-xl text-sm font-medium text-ink/80 hover:bg-sage" onClick={() => { navigate('/login'); setMobileOpen(false); }}>
              {t('nav_login')}
            </button>
          )}
          {role !== 'visitor' && (
            <button className="text-left px-3 py-2.5 rounded-xl text-sm font-medium text-ink/80 hover:bg-sage" onClick={() => { onLogout(); setMobileOpen(false); }}>
              {t('nav_logout')}
            </button>
          )}
        </div>
      )}
    </header>
  );
}

// ---- Footer ----
function Footer({ onShowEmails }) {
  const t = useT();
  return (
    <footer className="mt-24 bg-sage/60 border-t border-sage">
      <div className="max-w-7xl mx-auto px-4 md:px-8 py-12 grid md:grid-cols-3 gap-8">
        <div>
          <Logo size="md" />
          <p className="text-sm text-ink/60 mt-3 leading-relaxed max-w-xs">Centru de nutriție sportivă și educație alimentară. Meniuri personalizate pe baza analizelor tale.</p>
        </div>
        <div className="text-sm">
          <div className="font-semibold text-ink/80 mb-3 uppercase tracking-[0.12em] text-xs">Linkuri</div>
          <ul className="space-y-2">
            <li><a href="#/plans" className="text-ink/65 hover:text-green-primary" onClick={(e) => { e.preventDefault(); navigate('/plans'); }}>{t('nav_plans')}</a></li>
            <li><a href="#/login" className="text-ink/65 hover:text-green-primary" onClick={(e) => { e.preventDefault(); navigate('/login'); }}>{t('nav_login')}</a></li>
            <li><a href="#/terms" className="text-ink/65 hover:text-green-primary" onClick={(e) => { e.preventDefault(); navigate('/terms'); }}>{t('terms_title')}</a></li>
            <li><a href="#/admin/login" className="text-ink/45 hover:text-green-primary text-xs" onClick={(e) => { e.preventDefault(); navigate('/admin/login'); }}>Acces nutriționist</a></li>
          </ul>
        </div>
        <div className="text-sm">
          <div className="font-semibold text-ink/80 mb-3 uppercase tracking-[0.12em] text-xs">Demo</div>
          <button onClick={onShowEmails} className="text-ink/65 hover:text-green-primary inline-flex items-center gap-1.5">
            <Icon name="mail" size={14} /> {t('emails_demo_btn')}
          </button>
          <div className="text-xs text-ink/45 mt-4">© 2026 Silueta Naturală — Demo prototip</div>
        </div>
      </div>
    </footer>
  );
}

// ---- Demo Mode Switcher (floating) ----
function DemoSwitcher() {
  const t = useT();
  const { demoMode, setDemoMode } = useApp();
  const [open, setOpen] = React.useState(false);

  const modes = [
    { value: 'visitor', label: t('demo_visitor'), icon: 'globe', target: '/' },
    { value: 'fresh_purchase', label: t('demo_fresh'), icon: 'gift', target: '/account' },
    { value: 'first_menu', label: t('demo_first'), icon: 'spark', target: '/account' },
    { value: 'active', label: t('demo_active'), icon: 'leaf', target: '/account' },
    { value: 'expired_labs', label: t('demo_expired'), icon: 'alert', target: '/account' },
    { value: 'family', label: t('demo_family'), icon: 'user', target: '/profiles' },
    { value: 'admin', label: t('demo_admin'), icon: 'user', target: '/admin' },
  ];
  const current = modes.find(m => m.value === demoMode) || modes[0];

  const onPick = (m) => {
    setDemoMode(m.value);
    setOpen(false);
    navigate(m.target);
  };

  return (
    <div className="fixed bottom-4 right-4 z-50">
      {open && (
        <div className="absolute bottom-full right-0 mb-2 bg-white rounded-2xl shadow-card border border-sage w-72 overflow-hidden fade-up">
          <div className="px-4 py-3 border-b border-sage bg-cream/40">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-olive">{t('demo_title')}</div>
            <div className="text-sm text-ink/60 mt-0.5">Schimbă rolul / starea demo</div>
          </div>
          <div className="p-1.5">
            {modes.map(m => (
              <button key={m.value} onClick={() => onPick(m)}
                className={cls("w-full flex items-center gap-3 text-left px-3 py-2.5 rounded-xl text-sm transition-colors",
                  demoMode === m.value ? 'bg-green-primary/10 text-green-dark font-semibold' : 'hover:bg-sage')}>
                <span className={cls("w-7 h-7 rounded-lg flex items-center justify-center",
                  demoMode === m.value ? 'bg-green-primary text-white' : 'bg-sage text-ink/60')}>
                  <Icon name={m.icon} size={14} />
                </span>
                <span>{m.label}</span>
                {demoMode === m.value && <Icon name="check" size={14} className="ml-auto text-green-primary" strokeWidth={2.4} />}
              </button>
            ))}
          </div>
        </div>
      )}
      <button onClick={() => setOpen(o => !o)}
        className={cls("flex items-center gap-2.5 bg-ink text-white pl-2.5 pr-4 py-2 rounded-full shadow-card hover:bg-black transition-colors",
          open && 'ring-2 ring-lime')}>
        <span className="w-7 h-7 rounded-full bg-lime text-ink flex items-center justify-center">
          <Icon name={current.icon} size={14} strokeWidth={2.2} />
        </span>
        <span className="text-sm font-medium">{current.label}</span>
        <Icon name="chevron_down" size={14} className={cls("transition-transform", open && 'rotate-180')} />
      </button>
    </div>
  );
}

// ---- Email preview (reusable) ----
function EmailPreview({ kind = 'welcome', compact = false }) {
  const t = useT();
  const presets = {
    welcome: { from: 'hello@silueta-naturala.ro', subject: t('email_welcome_subject'),
      bodyKind: 'welcome', cta: { label: t('email_activate'), to: '/signup?token=demo' }, attach: null },
    menu: { from: 'hello@silueta-naturala.ro', subject: t('email_menu_subject'),
      bodyKind: 'menu', cta: { label: t('email_open_app'), to: '/account/menu/3' }, attach: t('email_pdf_attached') },
    lab: { from: 'hello@silueta-naturala.ro', subject: t('email_lab_subject'),
      bodyKind: 'lab', cta: { label: t('block_cta'), to: '/onboarding' }, attach: null },
    renew: { from: 'hello@silueta-naturala.ro', subject: t('email_renew_subject'),
      bodyKind: 'renew', cta: { label: t('email_renew'), to: '/account/renew' }, attach: null },
    reset: { from: 'hello@silueta-naturala.ro', subject: t('email_reset_subject'),
      bodyKind: 'reset', cta: { label: t('email_reset'), to: '/reset-password?token=demo' }, attach: null },
  };
  const p = presets[kind] || presets.welcome;
  return (
    <div className="bg-white rounded-2xl border border-sage shadow-soft overflow-hidden">
      <div className="px-5 py-3 border-b border-sage bg-cream/50 flex items-center gap-3 flex-wrap">
        <div className="w-8 h-8 rounded-full bg-green-primary text-white flex items-center justify-center text-xs font-bold">SN</div>
        <div className="min-w-0">
          <div className="text-xs text-ink/55">{t('email_from')} <span className="text-ink/80">{p.from}</span></div>
          <div className="font-serif font-semibold text-ink truncate">{p.subject}</div>
        </div>
      </div>
      <div className={cls("px-6 relative", compact ? 'py-5' : 'py-7')}>
        {p.bodyKind === 'welcome' && (
          <div className="space-y-4">
            <p className="text-sm text-ink/80">Bună,</p>
            <p className="text-sm text-ink/80">Mulțumim pentru achiziție! Pentru a începe, activează contul tău și completează formularul personalizat.</p>
            <Button variant="primary" onClick={() => navigate(p.cta.to)}>{p.cta.label}</Button>
            <p className="text-xs text-ink/45">Linkul expiră în 48 de ore.</p>
          </div>
        )}
        {p.bodyKind === 'menu' && (
          <div className="space-y-4">
            <p className="text-sm text-ink/80">Bună Ana,</p>
            <p className="text-sm text-ink/80">Meniul tău pe 7 zile pentru săptămâna 3 este gata. Îl găsești atașat ca PDF și disponibil în cont.</p>
            <div className="bg-sage/60 rounded-xl px-4 py-3 flex items-center gap-3">
              <Icon name="paperclip" size={18} className="text-olive" />
              <div>
                <div className="text-sm font-semibold">{p.attach}</div>
                <div className="text-xs text-ink/55">PDF · 1.2 MB</div>
              </div>
            </div>
            <Button variant="primary" onClick={() => navigate(p.cta.to)}>{p.cta.label}</Button>
          </div>
        )}
        {p.bodyKind === 'lab' && (
          <div className="space-y-4">
            <div className="bg-coral/10 border border-coral/30 rounded-xl p-3 flex gap-3">
              <Icon name="alert" size={18} className="text-coral flex-shrink-0" />
              <div className="text-sm text-ink/80">Analizele tale expiră în 14 zile.</div>
            </div>
            <p className="text-sm text-ink/80">Pentru a continua să primești meniuri precise, te rugăm să adaugi analize noi.</p>
            <Button variant="coral" onClick={() => navigate(p.cta.to)}>{p.cta.label}</Button>
          </div>
        )}
        {p.bodyKind === 'renew' && (
          <div className="space-y-4">
            <p className="text-sm text-ink/80">Bună Ana,</p>
            <p className="text-sm text-ink/80">Pachetul tău s-a încheiat. Continuăm împreună?</p>
            <Button variant="primary" onClick={() => navigate(p.cta.to)}>{p.cta.label}</Button>
          </div>
        )}
        {p.bodyKind === 'reset' && (
          <div className="space-y-4">
            <p className="text-sm text-ink/80">Pentru a-ți reseta parola, apasă butonul de mai jos. Linkul expiră în 60 de minute.</p>
            <Button variant="primary" onClick={() => navigate(p.cta.to)}>{p.cta.label}</Button>
            <p className="text-xs text-ink/45">Dacă nu ai cerut tu, ignoră acest email.</p>
          </div>
        )}
      </div>
    </div>
  );
}

function EmailGalleryModal({ open, onClose }) {
  const t = useT();
  const kinds = [
    { key: 'welcome', label: t('email_welcome_subject') },
    { key: 'menu', label: t('email_menu_subject') },
    { key: 'lab', label: t('email_lab_subject') },
    { key: 'renew', label: t('email_renew_subject') },
    { key: 'reset', label: t('email_reset_subject') },
  ];
  const [active, setActive] = React.useState('welcome');
  return (
    <Modal open={open} onClose={onClose} title={t('emails_demo_btn')} size="xl">
      <div className="grid md:grid-cols-[200px_1fr] gap-4">
        <div className="flex md:flex-col gap-1 overflow-x-auto pb-1">
          {kinds.map(k => (
            <button key={k.key} onClick={() => setActive(k.key)}
              className={cls("text-left text-xs px-3 py-2 rounded-xl whitespace-nowrap md:whitespace-normal flex-shrink-0 md:flex-shrink",
                active === k.key ? 'bg-green-primary/10 text-green-dark font-semibold' : 'hover:bg-sage text-ink/65')}>
              {k.label}
            </button>
          ))}
        </div>
        <div>
          <EmailPreview kind={active} />
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, {
  navigate, RouterContext, RouterProvider, useRouter, matchRoute,
  AppContext, AppProvider, useApp, DEMO_MODES,
  Logo, LocaleToggle, Nav, Footer, DemoSwitcher, EmailPreview, EmailGalleryModal,
});
// Marketing & legal pages: Landing, Plans, Checkout modal, Success, Terms

function LandingPage() {
  const t = useT();
  const [emailsOpen, setEmailsOpen] = React.useState(false);

  return (
    <div>
      {/* HERO */}
      <section className="relative">
        <HeroBlobs />
        <div className="max-w-7xl mx-auto px-4 md:px-8 pt-12 md:pt-20 pb-16 md:pb-28 grid md:grid-cols-2 gap-12 items-center relative">
          <div>
            <div className="inline-flex items-center gap-2 bg-white/70 border border-sage rounded-full px-3 py-1.5 mb-6 backdrop-blur-sm">
              <span className="w-1.5 h-1.5 rounded-full bg-lime animate-pulse" />
              <span className="text-xs font-medium text-olive">Personalizat după analizele tale</span>
            </div>
            <h1 className="h1 text-5xl md:text-6xl lg:text-7xl leading-[0.95] mb-6 whitespace-pre-line">
              {t('landing_hero_title')}
            </h1>
            <p className="text-ink/65 text-lg md:text-xl max-w-lg leading-relaxed mb-8">{t('landing_hero_sub')}</p>
            <div className="flex flex-wrap gap-3">
              <Button variant="primary" onClick={() => navigate('/plans')}>
                {t('landing_cta_primary')}
                <Icon name="arrow_right" size={16} />
              </Button>
              <Button variant="ghost" onClick={() => document.getElementById('how').scrollIntoView({ behavior: 'smooth', block: 'start' })}>
                {t('landing_cta_secondary')}
              </Button>
            </div>
            <div className="flex items-center gap-4 mt-10 text-sm text-ink/60">
              <div className="flex -space-x-2">
                {['🌱', '🥗', '🍎'].map((e, i) => (
                  <div key={i} className="w-8 h-8 rounded-full bg-cream border-2 border-cream flex items-center justify-center text-base">{e}</div>
                ))}
              </div>
              <span>+200 de planuri personalizate livrate</span>
            </div>
          </div>

          {/* Hero collage */}
          <div className="relative">
            <div className="grid grid-cols-6 grid-rows-6 gap-3 h-[480px]">
              <div className="col-span-4 row-span-4 rounded-3xl overflow-hidden">
                <FoodImage kind="bowl" size="lg" className="!h-full !w-full" />
              </div>
              <div className="col-span-2 row-span-3 rounded-3xl overflow-hidden">
                <FoodImage kind="leaf" size="lg" className="!h-full !w-full" />
              </div>
              <div className="col-span-2 row-span-3 rounded-3xl overflow-hidden">
                <FoodImage kind="fruit" size="lg" className="!h-full !w-full" />
              </div>
              <div className="col-span-3 row-span-2 rounded-3xl overflow-hidden">
                <FoodImage kind="grain" size="lg" className="!h-full !w-full" />
              </div>
              <div className="col-span-3 row-span-2 rounded-3xl overflow-hidden">
                <FoodImage kind="drink" size="lg" className="!h-full !w-full" />
              </div>
            </div>
            {/* Floating sample card */}
            <div className="absolute -bottom-6 -left-4 md:-left-12 bg-white rounded-2xl shadow-card p-4 max-w-[260px] border border-sage">
              <div className="flex items-center gap-2 mb-2">
                <div className="w-9 h-9 rounded-full bg-sage flex items-center justify-center"><Icon name="leaf" size={16} className="text-green-primary" /></div>
                <div className="text-xs">
                  <div className="font-semibold text-ink/85">Astăzi mănânci</div>
                  <div className="text-ink/55">1800 kcal · vegetarian</div>
                </div>
              </div>
              <div className="text-xs text-ink/70 leading-relaxed">2 ouă fierte · ovăz cu lapte vegetal · banană · ceai verde</div>
            </div>
          </div>
        </div>
      </section>

      {/* FEATURES */}
      <section className="max-w-7xl mx-auto px-4 md:px-8 py-12 md:py-20">
        <SectionHead eyebrow="DE CE SILUETA" title={t('landing_features_title')} />
        <div className="grid md:grid-cols-3 gap-6 mt-10">
          {[
            { icon: 'spark', tone: 'green', title: t('feat1_title'), body: t('feat1_body'), kind: 'leaf' },
            { icon: 'leaf', tone: 'lime', title: t('feat2_title'), body: t('feat2_body'), kind: 'grain' },
            { icon: 'mail', tone: 'purple', title: t('feat3_title'), body: t('feat3_body'), kind: 'bowl' },
          ].map((f, i) => (
            <div key={i} className="card p-6 relative overflow-hidden">
              <FoodImage kind={f.kind} size="lg" className="!h-32 mb-5" />
              <div className={cls("inline-flex items-center justify-center w-10 h-10 rounded-xl mb-3",
                f.tone === 'green' ? 'bg-green-primary/10 text-green-primary' :
                f.tone === 'lime' ? 'bg-lime/30 text-olive' : 'bg-purple-primary/10 text-purple-primary')}>
                <Icon name={f.icon} size={18} strokeWidth={2} />
              </div>
              <h3 className="serif text-xl font-semibold text-ink mb-1.5">{f.title}</h3>
              <p className="text-sm text-ink/65 leading-relaxed">{f.body}</p>
            </div>
          ))}
        </div>
      </section>

      {/* HOW IT WORKS */}
      <section id="how" className="bg-sage/50 py-16 md:py-24">
        <div className="max-w-7xl mx-auto px-4 md:px-8">
          <SectionHead eyebrow="PROCES SIMPLU" title={t('how_title')} align="center" />
          <div className="grid md:grid-cols-4 gap-6 mt-12 relative">
            {[
              { t: t('how_1_title'), b: t('how_1_body') },
              { t: t('how_2_title'), b: t('how_2_body') },
              { t: t('how_3_title'), b: t('how_3_body') },
              { t: t('how_4_title'), b: t('how_4_body') },
            ].map((s, i) => (
              <div key={i} className="relative">
                <div className="text-7xl serif text-purple-primary/15 leading-none mb-3 font-light">{i + 1}</div>
                <h3 className="serif text-lg font-semibold mb-1.5 text-ink">{s.t}</h3>
                <p className="text-sm text-ink/65 leading-relaxed max-w-xs">{s.b}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* TESTIMONIALS */}
      <section className="max-w-7xl mx-auto px-4 md:px-8 py-16 md:py-24">
        <SectionHead eyebrow="REZULTATE" title={t('testimonials_title')} />
        <div className="grid md:grid-cols-3 gap-5 mt-10">
          {[
            { name: 'Ioana M.', age: '32 ani', body: '„Primul plan care chiar a ținut cont de analizele mele. M-am simțit auzită."', tone: 'green' },
            { name: 'Vlad T.', age: '45 ani', body: '„Mi-a plăcut că primesc meniul ca PDF — îl scot la imprimat și îl pun pe frigider."', tone: 'beige' },
            { name: 'Maria C.', age: '28 ani', body: '„Ușor de urmat, cu mâncare reală. Am pierdut 4 kg fără să mă chinui."', tone: 'purple' },
          ].map((tt, i) => (
            <div key={i} className={cls("p-6 rounded-3xl",
              tt.tone === 'green' ? 'bg-green-primary text-white' :
              tt.tone === 'beige' ? 'bg-beige' : 'bg-purple-primary text-white')}>
              <Icon name="leaf" size={22} className={cls(tt.tone === 'beige' ? 'text-olive' : 'text-white/70')} />
              <p className="serif text-lg leading-snug my-4">{tt.body}</p>
              <div className={cls("text-sm", tt.tone === 'beige' ? 'text-ink/65' : 'text-white/80')}>
                <span className="font-semibold">{tt.name}</span> · {tt.age}
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* FAQ */}
      <section id="faq" className="max-w-3xl mx-auto px-4 md:px-8 py-16 md:py-24">
        <SectionHead eyebrow="ÎNTREBĂRI" title={t('faq_title')} align="center" />
        <div className="mt-10 divide-y divide-sage border-y border-sage">
          {[1, 2, 3, 4].map(n => (
            <details key={n} className="group py-4">
              <summary className="flex items-center justify-between gap-4">
                <span className="serif text-lg text-ink">{t(`faq_${n}_q`)}</span>
                <span className="w-8 h-8 rounded-full bg-sage flex-shrink-0 flex items-center justify-center group-open:rotate-180 transition-transform">
                  <Icon name="chevron_down" size={16} />
                </span>
              </summary>
              <div className="text-sm text-ink/70 leading-relaxed mt-3 pr-12">{t(`faq_${n}_a`)}</div>
            </details>
          ))}
        </div>
      </section>

      {/* CTA */}
      <section className="max-w-7xl mx-auto px-4 md:px-8 pb-16">
        <div className="relative overflow-hidden rounded-3xl bg-green-primary text-white px-8 md:px-16 py-14 md:py-20 text-center">
          <Blob color="#95C500" x="-60px" y="-60px" size={300} opacity={0.35} />
          <Blob color="#A874A8" x="auto" y="auto" size={300} opacity={0.25} className="!right-[-60px] !bottom-[-60px] !top-auto !left-auto" />
          <h2 className="serif text-3xl md:text-5xl font-semibold mb-4 relative">Începem astăzi?</h2>
          <p className="text-white/85 mb-7 relative max-w-lg mx-auto">Alege un pachet și primești primul meniu în 1–2 zile după ce completezi formularul.</p>
          <Button variant="lime" onClick={() => navigate('/plans')} className="relative">
            {t('landing_cta_primary')}
            <Icon name="arrow_right" size={16} />
          </Button>
        </div>
      </section>

      <Footer onShowEmails={() => setEmailsOpen(true)} />
      <EmailGalleryModal open={emailsOpen} onClose={() => setEmailsOpen(false)} />
    </div>
  );
}

// ---- Plans page ----
function PlansPage() {
  const t = useT();
  const { ana, demoMode } = useApp();
  const [checkoutPlan, setCheckoutPlan] = React.useState(null);
  const [blockOpen, setBlockOpen] = React.useState(false);
  const [emailsOpen, setEmailsOpen] = React.useState(false);

  const onBuy = (plan) => {
    if (demoMode === 'expired_labs' && ana.validations.labTests.status === 'expired') {
      setBlockOpen(true);
      return;
    }
    setCheckoutPlan(plan);
  };

  return (
    <div>
      <section className="max-w-7xl mx-auto px-4 md:px-8 py-12 md:py-20 relative">
        <HeroBlobs />
        <div className="text-center mb-14 relative">
          <h1 className="h1 text-4xl md:text-5xl mb-3">{t('plans_title')}</h1>
          <p className="text-ink/65 max-w-xl mx-auto">{t('plans_sub')}</p>
        </div>

        <div className="grid md:grid-cols-3 gap-6 max-w-5xl mx-auto relative">
          {window.PLANS.map(p => (
            <div key={p.key} className={cls("relative card p-7 flex flex-col",
              p.popular ? 'ring-2 ring-green-primary md:scale-[1.04]' : '')}>
              {p.popular && (
                <div className="absolute -top-3 left-1/2 -translate-x-1/2 bg-green-primary text-white text-[11px] uppercase tracking-[0.14em] font-bold px-3 py-1 rounded-full">
                  {t('plan_popular')}
                </div>
              )}
              <h3 className="serif text-xl text-purple-primary font-semibold">{p.name}</h3>
              <div className="my-5">
                <span className="serif text-5xl text-ink font-semibold">{p.priceRon}</span>
                <span className="text-ink/55 ml-1">RON</span>
              </div>
              <div className="text-sm text-ink/70 mb-5">
                <div>{t('plan_menus', p.menus)} · {t('plan_days', p.days)}</div>
                <div className="text-ink/50 text-xs mt-1">{t('plan_cadence')}</div>
              </div>
              <ul className="space-y-2.5 mb-7 text-sm">
                {p.perks.map(perk => (
                  <li key={perk} className="flex items-start gap-2">
                    <Icon name="check" size={16} className="text-green-primary mt-0.5 flex-shrink-0" strokeWidth={2.4} />
                    <span className="text-ink/75">{perk}</span>
                  </li>
                ))}
              </ul>
              <Button variant={p.popular ? 'primary' : 'outline'} className="w-full mt-auto" onClick={() => onBuy(p)}>
                {t('plan_buy')}
              </Button>
            </div>
          ))}
        </div>

        <div className="mt-14 max-w-5xl mx-auto">
          <div className="card p-7 md:p-8 relative overflow-hidden border border-purple-primary/15">
            <div className="absolute -top-20 -right-20 w-72 h-72 rounded-full" style={{ background: 'radial-gradient(circle, rgba(168,116,168,0.18), transparent 70%)' }} />
            <div className="relative grid md:grid-cols-[1fr_auto] gap-6 items-center">
              <div>
                <Pill tone="purple" className="mb-3"><Icon name="spark" size={11} /> {t('family_soon_badge')}</Pill>
                <h3 className="serif text-2xl md:text-3xl text-purple-primary font-semibold mb-2">{t('family_soon_title')}</h3>
                <p className="text-ink/70 max-w-2xl">{t('family_soon_subtitle')}</p>
              </div>
              <Button variant="outline" onClick={() => navigate('/profiles')}>
                <Icon name="arrow_right" size={14} /> {t('family_soon_cta')}
              </Button>
            </div>
          </div>
        </div>

        <div className="mt-12 text-center text-xs text-ink/50">
          Plata este securizată prin Stripe. Acest demo nu efectuează plăți reale.
        </div>
      </section>

      <Footer onShowEmails={() => setEmailsOpen(true)} />
      <CheckoutModal plan={checkoutPlan} onClose={() => setCheckoutPlan(null)} />
      <LabExpiredModal open={blockOpen} onClose={() => setBlockOpen(false)} />
      <EmailGalleryModal open={emailsOpen} onClose={() => setEmailsOpen(false)} />
    </div>
  );
}

// ---- Checkout (mock Stripe) ----
function CheckoutModal({ plan, onClose }) {
  const t = useT();
  const [email, setEmail] = React.useState('ana.popescu@example.com');
  const [card, setCard] = React.useState('4242 4242 4242 4242');
  const [exp, setExp] = React.useState('12 / 28');
  const [cvc, setCvc] = React.useState('123');
  const [loading, setLoading] = React.useState(false);

  if (!plan) return null;
  const onPay = () => {
    setLoading(true);
    setTimeout(() => { setLoading(false); onClose(); navigate('/checkout/success'); }, 900);
  };
  return (
    <Modal open={!!plan} onClose={onClose} title={t('checkout_title')} size="md"
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>{t('checkout_cancel')}</Button>
          <Button variant="primary" onClick={onPay} disabled={loading}>
            {loading ? '...' : `${t('checkout_pay')} · ${plan.priceRon} RON`}
          </Button>
        </>
      }>
      <div className="-mt-2 mb-4">
        <Pill tone="purple"><Icon name="lock" size={11} /> {t('checkout_demo')}</Pill>
      </div>
      <div className="bg-cream rounded-2xl p-4 mb-5 flex items-center justify-between">
        <div>
          <div className="font-serif font-semibold text-ink">{plan.name}</div>
          <div className="text-xs text-ink/55">{t('plan_menus', plan.menus)} · {t('plan_days', plan.days)}</div>
        </div>
        <div className="serif text-2xl font-semibold">{plan.priceRon} RON</div>
      </div>
      <div className="space-y-3">
        <Field label={t('checkout_email')}>
          <Input value={email} onChange={(e) => setEmail(e.target.value)} type="email" />
        </Field>
        <Field label={t('checkout_card')}>
          <Input value={card} onChange={(e) => setCard(e.target.value)} />
        </Field>
        <div className="grid grid-cols-2 gap-3">
          <Field label="Expirare">
            <Input value={exp} onChange={(e) => setExp(e.target.value)} />
          </Field>
          <Field label="CVC">
            <Input value={cvc} onChange={(e) => setCvc(e.target.value)} />
          </Field>
        </div>
      </div>
      <div className="text-xs text-ink/45 mt-4 flex items-center gap-1.5">
        <Icon name="lock" size={12} /> {t('checkout_secure')}
      </div>
    </Modal>
  );
}

// ---- Checkout success ----
function CheckoutSuccessPage() {
  const t = useT();
  return (
    <div>
      <section className="max-w-3xl mx-auto px-4 md:px-8 py-16 text-center relative">
        <HeroBlobs />
        <div className="relative">
          <div className="mx-auto w-20 h-20 rounded-full bg-green-primary text-white flex items-center justify-center mb-6">
            <Icon name="check" size={36} strokeWidth={2.6} />
          </div>
          <h1 className="h1 text-4xl md:text-5xl mb-3">{t('success_title')}</h1>
          <p className="text-ink/70 text-lg mb-12 max-w-md mx-auto">{t('success_sub')}</p>

          <div className="text-left">
            <div className="text-xs uppercase tracking-[0.14em] text-olive font-semibold mb-3">{t('success_email_preview')}</div>
            <EmailPreview kind="welcome" />
          </div>
        </div>
      </section>
      <Footer onShowEmails={() => {}} />
    </div>
  );
}

// ---- Terms ----
function TermsPage() {
  const t = useT();
  return (
    <div>
      <section className="max-w-3xl mx-auto px-4 md:px-8 py-12">
        <h1 className="h1 text-4xl md:text-5xl mb-6">{t('terms_title')}</h1>
        <div className="bg-coral/10 border border-coral/30 rounded-2xl p-5 mb-8">
          <div className="flex items-start gap-3">
            <Icon name="alert" size={20} className="text-coral flex-shrink-0 mt-0.5" />
            <div>
              <div className="font-semibold text-coral mb-1.5">{t('terms_disclaimer_title')}</div>
              <p className="text-sm text-ink/80 leading-relaxed">{t('terms_disclaimer')}</p>
            </div>
          </div>
        </div>

        <div className="prose prose-sm max-w-none text-ink/80 space-y-5 text-sm leading-relaxed">
          <div>
            <h3 className="serif text-xl text-purple-primary font-semibold">1. Obiectul contractului</h3>
            <p>Silueta Naturală oferă servicii de personalizare a meniurilor pe baza datelor furnizate de utilizator: parametri biometrici, analize de laborator, preferințe alimentare, alergii și un test psihologic scurt. Aceste meniuri au caracter informativ și de educație alimentară.</p>
          </div>
          <div>
            <h3 className="serif text-xl text-purple-primary font-semibold">2. Responsabilitatea utilizatorului</h3>
            <p>Utilizatorul declară că datele introduse sunt corecte, actuale și complete. Aplicația nu poate verifica veridicitatea informațiilor. Orice modificare a stării de sănătate (sarcină, intervenții chirurgicale, diagnostic nou) trebuie comunicată înainte de generarea unui meniu nou.</p>
          </div>
          <div>
            <h3 className="serif text-xl text-purple-primary font-semibold">3. Limitarea răspunderii</h3>
            <p>Recomandările generate nu înlocuiesc consultul medical. În caz de patologii cronice, utilizatorul se va consulta cu medicul specialist înainte de a urma orice plan alimentar.</p>
          </div>
          <div>
            <h3 className="serif text-xl text-purple-primary font-semibold">4. Plată și anulare</h3>
            <p>Plata se face în avans, pentru întregul pachet. Utilizatorul poate suspenda sau anula abonamentul oricând din contul personal. Meniurile rămase se livrează până la finalul perioadei contractuale.</p>
          </div>
          <div>
            <h3 className="serif text-xl text-purple-primary font-semibold">5. Confidențialitate</h3>
            <p>Datele medicale sunt criptate, stocate pe servere europene și accesibile doar nutriționistului responsabil. Aplicația nu partajează datele cu terți, în conformitate cu GDPR.</p>
          </div>
          <div>
            <h3 className="serif text-xl text-purple-primary font-semibold">6. Modificări</h3>
            <p>Termenii pot fi actualizați. Utilizatorii vor fi notificați prin email cu minimum 14 zile înainte de orice modificare semnificativă.</p>
          </div>
        </div>
      </section>
      <Footer onShowEmails={() => {}} />
    </div>
  );
}

// ---- Lab-expired blocking modal (used on plans, renew, dashboard) ----
function LabExpiredModal({ open, onClose }) {
  const t = useT();
  return (
    <Modal open={open} onClose={onClose} size="md"
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>{t('block_later')}</Button>
          <Button variant="coral" onClick={() => { onClose(); navigate('/onboarding?step=6'); }}>{t('block_cta')}</Button>
        </>
      }>
      <div className="text-center py-2">
        <div className="mx-auto w-16 h-16 rounded-full bg-coral/15 text-coral flex items-center justify-center mb-4">
          <Icon name="alert" size={28} />
        </div>
        <h3 className="h2 text-2xl mb-2">{t('block_title')}</h3>
        <p className="text-ink/70 max-w-md mx-auto">{t('block_body')}</p>
      </div>
    </Modal>
  );
}

Object.assign(window, {
  LandingPage, PlansPage, CheckoutModal, CheckoutSuccessPage, TermsPage, LabExpiredModal,
});
// Auth pages: Login, Signup (with T&C), Forgot, Reset

function LoginPage() {
  const t = useT();
  const { setDemoMode } = useApp();
  const [email, setEmail] = React.useState('ana.popescu@example.com');
  const [pwd, setPwd] = React.useState('demo1234');

  const submit = (e) => {
    e.preventDefault();
    setDemoMode('active');
    navigate('/account');
  };

  return (
    <AuthShell>
      <h1 className="h1 text-3xl md:text-4xl mb-2">{t('login_title')}</h1>
      <p className="text-ink/65 mb-7 text-sm">Autentifică-te pentru a vedea contul tău.</p>
      <form onSubmit={submit} className="space-y-4">
        <Field label={t('login_email')}><Input type="email" value={email} onChange={e => setEmail(e.target.value)} /></Field>
        <Field label={t('login_password')}><Input type="password" value={pwd} onChange={e => setPwd(e.target.value)} /></Field>
        <Button type="submit" variant="primary" className="w-full">{t('login_submit')}</Button>
      </form>
      <div className="mt-5 flex items-center justify-between text-sm">
        <a href="#/forgot-password" onClick={(e) => { e.preventDefault(); navigate('/forgot-password'); }} className="text-olive hover:underline">{t('login_forgot')}</a>
      </div>
      <div className="mt-3 text-xs text-ink/55">
        {t('login_signup_helper')}{' '}
        <a href="#/signup?token=demo" onClick={(e) => { e.preventDefault(); navigate('/signup?token=demo'); }} className="text-olive hover:underline">{t('login_signup_link')}</a>
      </div>
    </AuthShell>
  );
}

function SignupPage() {
  const t = useT();
  const [pwd, setPwd] = React.useState('');
  const [pwd2, setPwd2] = React.useState('');
  const [terms, setTerms] = React.useState(false);
  const [tcOpen, setTcOpen] = React.useState(false);
  const { setDemoMode } = useApp();
  const valid = pwd.length >= 6 && pwd === pwd2 && terms;

  const submit = (e) => {
    e.preventDefault();
    if (!valid) return;
    setDemoMode('first_menu');
    navigate('/onboarding');
  };

  return (
    <AuthShell rightSlot={
      <div className="card p-5">
        <div className="text-xs uppercase tracking-[0.12em] text-olive font-semibold mb-2">{t('signup_eligible')}</div>
        <div className="serif text-xl font-semibold text-ink">Pachet Standard</div>
        <div className="text-sm text-ink/55 mt-0.5">6 meniuri · 84 zile</div>
        <div className="mt-4 pt-4 border-t border-sage flex items-center gap-2 text-xs text-ink/55">
          <Icon name="check" size={14} className="text-green-primary" strokeWidth={2.4} /> Plată confirmată
        </div>
      </div>
    }>
      <h1 className="h1 text-3xl md:text-4xl mb-2">{t('signup_title')}</h1>
      <p className="text-ink/65 mb-7 text-sm">{t('signup_sub')}</p>
      <form onSubmit={submit} className="space-y-4">
        <Field label={t('signup_password')}><Input type="password" value={pwd} onChange={e => setPwd(e.target.value)} /></Field>
        <Field label={t('signup_password_confirm')} error={pwd2 && pwd !== pwd2 ? 'Parolele nu se potrivesc' : null}>
          <Input type="password" value={pwd2} onChange={e => setPwd2(e.target.value)} />
        </Field>
        <div className="pt-2">
          <Checkbox checked={terms} onChange={setTerms}
            label={<span>{t('signup_terms_label')}{' '}
              <button type="button" onClick={() => setTcOpen(true)} className="text-olive hover:underline">{t('signup_terms_link')}</button>
            </span>}
          />
        </div>
        <Button type="submit" variant="primary" className="w-full" disabled={!valid}>{t('signup_submit')}</Button>
      </form>

      <Modal open={tcOpen} onClose={() => setTcOpen(false)} title={t('terms_title')} size="lg"
        footer={<Button variant="primary" onClick={() => { setTerms(true); setTcOpen(false); }}>{t('signup_terms_label')} {t('signup_terms_link')}</Button>}>
        <div className="bg-coral/10 border border-coral/30 rounded-2xl p-4 mb-5">
          <div className="flex items-start gap-3">
            <Icon name="alert" size={18} className="text-coral flex-shrink-0 mt-0.5" />
            <div>
              <div className="font-semibold text-coral mb-1">{t('terms_disclaimer_title')}</div>
              <p className="text-sm text-ink/80 leading-relaxed">{t('terms_disclaimer')}</p>
            </div>
          </div>
        </div>
        <div className="text-sm text-ink/75 space-y-3 leading-relaxed">
          <p>1. <strong>Obiectul contractului.</strong> Silueta Naturală oferă servicii de personalizare a meniurilor pe baza datelor introduse de utilizator.</p>
          <p>2. <strong>Responsabilitatea utilizatorului.</strong> Utilizatorul declară că datele furnizate sunt corecte și actuale.</p>
          <p>3. <strong>Limitarea răspunderii.</strong> Recomandările generate nu înlocuiesc consultul medical.</p>
          <p>4. <strong>Confidențialitate.</strong> Datele sunt stocate criptat, accesibile doar nutriționistului. GDPR aplicabil.</p>
          <p className="text-xs text-ink/55">Vezi și <a href="#/terms" onClick={(e) => { e.preventDefault(); setTcOpen(false); navigate('/terms'); }} className="text-olive hover:underline">pagina completă</a>.</p>
        </div>
      </Modal>
    </AuthShell>
  );
}

function ForgotPasswordPage() {
  const t = useT();
  const [email, setEmail] = React.useState('');
  const [sent, setSent] = React.useState(false);

  return (
    <AuthShell>
      <h1 className="h1 text-3xl md:text-4xl mb-2">{t('forgot_title')}</h1>
      <p className="text-ink/65 mb-7 text-sm">{t('forgot_sub')}</p>
      {!sent ? (
        <form onSubmit={(e) => { e.preventDefault(); setSent(true); }} className="space-y-4">
          <Field label={t('login_email')}><Input type="email" value={email} onChange={e => setEmail(e.target.value)} /></Field>
          <Button type="submit" variant="primary" className="w-full">{t('forgot_submit')}</Button>
        </form>
      ) : (
        <div>
          <div className="bg-green-primary/10 border border-green-primary/30 rounded-2xl p-4 mb-5 flex gap-3">
            <Icon name="check" size={18} className="text-green-primary flex-shrink-0 mt-0.5" strokeWidth={2.4} />
            <p className="text-sm text-ink/80">{t('forgot_success')}</p>
          </div>
          <div className="text-xs uppercase tracking-[0.14em] text-olive font-semibold mb-3">{t('success_email_preview')}</div>
          <EmailPreview kind="reset" />
        </div>
      )}
    </AuthShell>
  );
}

function ResetPasswordPage() {
  const t = useT();
  const toast = useToast();
  const [pwd, setPwd] = React.useState('');
  const [pwd2, setPwd2] = React.useState('');
  const valid = pwd.length >= 6 && pwd === pwd2;

  const submit = (e) => {
    e.preventDefault();
    if (!valid) return;
    toast.push(t('reset_success'));
    setTimeout(() => navigate('/login'), 600);
  };
  return (
    <AuthShell>
      <h1 className="h1 text-3xl md:text-4xl mb-2">{t('reset_title')}</h1>
      <form onSubmit={submit} className="space-y-4 mt-7">
        <Field label={t('reset_new')}><Input type="password" value={pwd} onChange={e => setPwd(e.target.value)} /></Field>
        <Field label={t('reset_confirm')} error={pwd2 && pwd !== pwd2 ? 'Parolele nu se potrivesc' : null}>
          <Input type="password" value={pwd2} onChange={e => setPwd2(e.target.value)} />
        </Field>
        <Button type="submit" variant="primary" className="w-full" disabled={!valid}>{t('reset_submit')}</Button>
      </form>
    </AuthShell>
  );
}

function AdminLoginPage() {
  const t = useT();
  const { setDemoMode } = useApp();
  const submit = (e) => {
    e.preventDefault();
    setDemoMode('admin');
    navigate('/admin');
  };
  return (
    <AuthShell variant="admin">
      <Pill tone="purple" className="mb-3">Acces nutriționist</Pill>
      <h1 className="h1 text-3xl md:text-4xl mb-2">{t('adm_login_title')}</h1>
      <form onSubmit={submit} className="space-y-4 mt-7">
        <Field label={t('login_email')}><Input type="email" defaultValue="dr@silueta-naturala.ro" /></Field>
        <Field label={t('login_password')}><Input type="password" defaultValue="demo1234" /></Field>
        <Button type="submit" variant="primary" className="w-full">{t('login_submit')}</Button>
      </form>
    </AuthShell>
  );
}

function AuthShell({ children, rightSlot, variant = 'default' }) {
  return (
    <div className="min-h-[calc(100vh-4rem)] grid lg:grid-cols-2 relative overflow-hidden">
      <div className="flex items-center justify-center p-6 md:p-12 relative">
        <Blob color="#95C500" x="-100px" y="-100px" size={400} opacity={0.15} />
        <div className="w-full max-w-md relative">
          {children}
          {rightSlot && <div className="lg:hidden mt-8">{rightSlot}</div>}
        </div>
      </div>
      <div className="hidden lg:flex items-center justify-center p-12 bg-sage/40 relative">
        <Blob color="#A874A8" x="auto" y="auto" size={500} opacity={0.18} className="!right-[-100px] !bottom-[-100px] !top-auto !left-auto" />
        {rightSlot ? (
          <div className="w-full max-w-sm relative">{rightSlot}</div>
        ) : (
          <div className="relative w-full max-w-sm">
            <FoodImage kind={variant === 'admin' ? 'leaf' : 'bowl'} size="lg" className="!h-72 mb-4" />
            <div className="card p-6">
              <div className="serif text-2xl text-purple-primary font-semibold leading-tight">
                {variant === 'admin' ? 'Vezi toți clienții într-un singur loc' : 'Mâncare bună, gândită pentru tine'}
              </div>
              <p className="text-sm text-ink/65 mt-2">
                {variant === 'admin' ? 'Status validări, abonamente și meniuri — totul la zi.' : 'Personalizat după analizele tale, livrat la 14 zile.'}
              </p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { LoginPage, SignupPage, ForgotPasswordPage, ResetPasswordPage, AdminLoginPage, AuthShell });
// Onboarding — 7 steps + completion screen

function OnboardingPage() {
  const t = useT();
  const { ana } = useApp();
  const { query } = useRouter();
  const [returning, setReturning] = React.useState(false);
  const initStep = query.step ? Math.max(1, Math.min(7, parseInt(query.step, 10))) : 1;
  const [step, setStep] = React.useState(initStep);

  // form state — pre-filled from Ana when in returning mode, blank when first-time
  const empty = {
    height: '', dob: '', sex: 'female', weight: '', activity: 'moderate',
    goal: 'maintain', wakeUp: '07:00', fasting: false, fastingStart: '', fastingEnd: '',
    prefs: { vegan: false, vegetarian: false, lactoseIntolerant: false, glutenIntolerant: false, dislikesSpicy: false },
    allergies: [], dislikedFoods: [], dislikedDrinks: [],
    labDate: '2026-04-15', labValues: {},
    psych: {},
  };
  const filled = {
    height: 165, dob: '1991-03-12', sex: 'female', weight: 75, activity: 'moderate',
    goal: 'lose_weight', wakeUp: '07:00', fasting: false, fastingStart: '', fastingEnd: '',
    prefs: { ...ana.preferences },
    allergies: ['Nuci'], dislikedFoods: ['Broccoli', 'Vinete'], dislikedDrinks: ['Cafea'],
    labDate: '2026-04-15',
    labValues: { vitamin_d: 15, hemoglobin: 13.2, tsh: 2.1, glucose: 92, cholesterol: 195 },
    psych: { anxiety: { q0: 3, q1: 4, q2: 3 }, stress: { q0: 2, q1: 3, q2: 2 }, sleep: { q0: 1, q1: 2, q2: 1 }, energy: { q0: 2, q1: 2, q2: 2 }, mood: { q0: 2, q1: 2, q2: 1 } },
  };
  const [data, setData] = React.useState(returning ? filled : empty);
  React.useEffect(() => { setData(returning ? filled : empty); }, [returning]);

  const set = (patch) => setData(d => ({ ...d, ...patch }));

  const stepLabels = [t('onb_step1'), t('onb_step2'), t('onb_step3'), t('onb_step4'), t('onb_step5'), t('onb_step6'), t('onb_step7')];

  const next = () => step < 7 ? setStep(step + 1) : navigate('/onboarding/complete');
  const back = () => step > 1 ? setStep(step - 1) : navigate('/account');

  // computed kcal target (Mifflin-St Jeor)
  const targetKcal = React.useMemo(() => {
    const h = parseFloat(data.height) || 0;
    const w = parseFloat(data.weight) || 0;
    const age = data.dob ? Math.floor((new Date('2026-05-07') - new Date(data.dob)) / (365.25 * 86400000)) : 0;
    if (!h || !w || !age) return null;
    const bmr = data.sex === 'female' ? 10 * w + 6.25 * h - 5 * age - 161 : 10 * w + 6.25 * h - 5 * age + 5;
    const factors = { sedentary: 1.2, light: 1.375, moderate: 1.55, active: 1.725, very_active: 1.9 };
    const tdee = bmr * (factors[data.activity] || 1.55);
    const adj = data.goal === 'lose_weight' ? -500 : data.goal === 'gain_muscle' ? 300 : 0;
    return Math.round(tdee + adj);
  }, [data.height, data.weight, data.dob, data.sex, data.activity, data.goal]);

  return (
    <div className="min-h-[calc(100vh-4rem)] bg-cream">
      <div className="max-w-4xl mx-auto px-4 md:px-8 py-8">
        {/* Header / demo toggle */}
        <div className="flex flex-wrap items-center justify-between gap-3 mb-6">
          <div className="flex items-center gap-3 text-sm">
            <span className="text-ink/55">{t('onb_demo_label')}</span>
            <div className="inline-flex bg-sage rounded-full p-0.5">
              <button onClick={() => setReturning(false)} className={cls("px-3 py-1.5 rounded-full text-xs font-semibold", !returning ? 'bg-white text-green-primary shadow-sm' : 'text-ink/55')}>{t('onb_demo_first')}</button>
              <button onClick={() => setReturning(true)} className={cls("px-3 py-1.5 rounded-full text-xs font-semibold", returning ? 'bg-white text-green-primary shadow-sm' : 'text-ink/55')}>{t('onb_demo_returning')}</button>
            </div>
          </div>
          <Button variant="ghost" size="sm" onClick={() => { navigate('/account'); }}>
            <Icon name="check" size={14} /> {t('onb_save')}
          </Button>
        </div>

        {/* Stepper */}
        <div className="card p-5 mb-6">
          <div className="flex items-center justify-between mb-3">
            <div className="text-sm font-semibold text-ink">{t('onb_step', step, 7)} · {stepLabels[step - 1]}</div>
            <div className="text-xs text-ink/55">{Math.round((step / 7) * 100)}%</div>
          </div>
          <Progress value={step} max={7} />
          <div className="hidden md:flex items-center justify-between mt-4 text-[11px] text-ink/55 gap-2">
            {stepLabels.map((lbl, i) => (
              <button key={i} onClick={() => setStep(i + 1)} className={cls("flex-1 truncate text-center py-1 px-1 rounded", step === i + 1 ? 'text-green-primary font-bold' : 'hover:text-ink/80')}>
                {i + 1}. {lbl}
              </button>
            ))}
          </div>
        </div>

        {returning && (
          <div className="bg-green-primary/10 border border-green-primary/25 rounded-2xl p-4 mb-5 flex items-center gap-3 text-sm">
            <Icon name="check" size={18} className="text-green-primary" strokeWidth={2.4} />
            <span className="text-ink/75">{t('onb_validuntil', '2026-10-15')}</span>
          </div>
        )}

        {step === 1 && <Step1 data={data} set={set} returning={returning} targetKcal={targetKcal} />}
        {step === 2 && <Step2 data={data} set={set} />}
        {step === 3 && <Step3 data={data} set={set} />}
        {step === 4 && <Step4 data={data} set={set} />}
        {step === 5 && <Step5 data={data} set={set} />}
        {step === 6 && <Step6 data={data} set={set} />}
        {step === 7 && <Step7 data={data} set={set} />}

        <div className="flex items-center justify-between mt-6 gap-3">
          <Button variant="outline" onClick={back}>
            <Icon name="arrow_left" size={14} /> {t('onb_back')}
          </Button>
          <Button variant="primary" onClick={next}>
            {step === 7 ? t('onb_finish') : t('onb_next')}
            <Icon name="arrow_right" size={14} />
          </Button>
        </div>
      </div>
    </div>
  );
}

function Step1({ data, set, returning, targetKcal }) {
  const t = useT();
  const acts = [
    { value: 'sedentary', label: t('act_sedentary'), description: t('act_sedentary_d') },
    { value: 'light', label: t('act_light'), description: t('act_light_d') },
    { value: 'moderate', label: t('act_moderate'), description: t('act_moderate_d') },
    { value: 'active', label: t('act_active'), description: t('act_active_d') },
    { value: 'very_active', label: t('act_very'), description: t('act_very_d') },
  ];
  const goals = [
    { value: 'lose_weight', label: t('goal_lose') },
    { value: 'maintain', label: t('goal_maintain') },
    { value: 'gain_muscle', label: t('goal_muscle') },
    { value: 'improve_health', label: t('goal_health') },
  ];

  return (
    <div className="card p-6 md:p-8 space-y-6">
      <div>
        <h2 className="h2 text-2xl mb-1">{t('onb_step1')}</h2>
        <p className="text-sm text-ink/60">Date despre tine — folosite pentru a calcula caloriile țintă.</p>
      </div>
      {!returning && (
        <div className="bg-sage/50 rounded-2xl p-3 flex items-center gap-2.5 text-xs">
          <Icon name="check" size={14} className="text-green-primary" strokeWidth={2.4} /> {t('onb_tc_reminder')}
        </div>
      )}
      {!returning && (
        <div className="grid md:grid-cols-3 gap-4">
          <Field label={t('onb_height')}><Input type="number" value={data.height} onChange={e => set({ height: e.target.value })} placeholder="165" /></Field>
          <Field label={t('onb_dob')}><Input type="date" value={data.dob} onChange={e => set({ dob: e.target.value })} /></Field>
          <Field label={t('onb_sex')}>
            <RadioGroup value={data.sex} onChange={v => set({ sex: v })} layout="row" name="sex"
              options={[{ value: 'female', label: t('onb_sex_f') }, { value: 'male', label: t('onb_sex_m') }]} />
          </Field>
        </div>
      )}
      <div className="grid md:grid-cols-2 gap-4">
        <Field label={t('onb_weight')}><Input type="number" value={data.weight} onChange={e => set({ weight: e.target.value })} placeholder="75" /></Field>
        <Field label={t('onb_wakeup')}><Input type="time" value={data.wakeUp} onChange={e => set({ wakeUp: e.target.value })} /></Field>
      </div>
      <Field label={t('onb_activity')}>
        <RadioGroup value={data.activity} onChange={v => set({ activity: v })} options={acts} name="activity" />
      </Field>
      <Field label={t('onb_goal')}>
        <RadioGroup value={data.goal} onChange={v => set({ goal: v })} options={goals} layout="row" name="goal" />
      </Field>
      <div className="border border-sage rounded-2xl p-4">
        <Switch checked={data.fasting} onChange={v => set({ fasting: v })} label={t('onb_fasting')} sublabel="Adaptăm meniul pentru perioada de post" />
        {data.fasting && (
          <div className="grid md:grid-cols-2 gap-4 mt-4">
            <Field label={t('onb_fasting_start')}><Input type="date" value={data.fastingStart} onChange={e => set({ fastingStart: e.target.value })} /></Field>
            <Field label={t('onb_fasting_end')}><Input type="date" value={data.fastingEnd} onChange={e => set({ fastingEnd: e.target.value })} /></Field>
          </div>
        )}
      </div>

      {/* Live kcal */}
      <div className="bg-green-primary text-white rounded-2xl p-5 flex items-center justify-between">
        <div>
          <div className="text-xs uppercase tracking-[0.14em] text-white/75 font-semibold">{t('onb_target_kcal')}</div>
          <div className="serif text-3xl md:text-4xl font-semibold mt-1">{targetKcal || '—'} <span className="text-base text-white/75 font-sans font-medium">{t('onb_kcal_per_day')}</span></div>
        </div>
        <Icon name="flame" size={32} className="text-lime" />
      </div>
    </div>
  );
}

function Step2({ data, set }) {
  const t = useT();
  const items = [
    ['vegan', t('onb_pref_vegan')],
    ['vegetarian', t('onb_pref_vegetarian')],
    ['lactoseIntolerant', t('onb_pref_lactose')],
    ['glutenIntolerant', t('onb_pref_gluten')],
    ['dislikesSpicy', t('onb_pref_spicy'), true],  // special: switch label is positive ("îmi place picantul" = inverse)
  ];
  return (
    <div className="card p-6 md:p-8 space-y-3">
      <div>
        <h2 className="h2 text-2xl mb-1">{t('onb_step2')}</h2>
        <p className="text-sm text-ink/60 mb-4">Alegeri rapide despre stilul tău alimentar.</p>
      </div>
      <div className="divide-y divide-sage">
        {items.map(([k, label, inverse]) => (
          <div key={k} className="flex items-center justify-between py-3.5">
            <div className="text-sm font-medium text-ink">{label}</div>
            <Switch
              checked={inverse ? !data.prefs[k] : data.prefs[k]}
              onChange={v => set({ prefs: { ...data.prefs, [k]: inverse ? !v : v } })}
            />
          </div>
        ))}
      </div>
    </div>
  );
}

function Step3({ data, set }) {
  const t = useT();
  const [search, setSearch] = React.useState('');
  const list = window.ALLERGIES.filter(a => a.toLowerCase().includes(search.toLowerCase()));
  const toggle = (a) => {
    const has = data.allergies.includes(a);
    set({ allergies: has ? data.allergies.filter(x => x !== a) : [...data.allergies, a] });
  };
  return (
    <div className="card p-6 md:p-8 space-y-4">
      <div>
        <h2 className="h2 text-2xl mb-1">{t('onb_step3')}</h2>
        <p className="text-sm text-ink/60">{t('onb_allergies_helper')}</p>
      </div>
      <div className="relative max-w-md">
        <Icon name="search" size={16} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-ink/40" />
        <Input value={search} onChange={e => setSearch(e.target.value)} placeholder={t('onb_search')} className="pl-10" />
      </div>
      <div className="text-xs text-ink/55">{t('onb_selected', data.allergies.length)}</div>
      <div className="flex flex-wrap gap-2">
        {list.map(a => {
          const on = data.allergies.includes(a);
          return (
            <button key={a} onClick={() => toggle(a)}
              className={cls("px-3.5 py-2 rounded-full text-sm font-medium border-2 transition-all",
                on ? 'bg-coral text-white border-coral' : 'bg-white text-ink/75 border-sage hover:border-coral/50')}>
              {on && <Icon name="check" size={12} strokeWidth={2.5} className="inline mr-1" />}
              {a}
            </button>
          );
        })}
      </div>
      {data.allergies.length === 0 && (
        <div className="border-2 border-dashed border-sage rounded-2xl p-6 text-center text-sm text-ink/55">
          <Icon name="leaf" size={20} className="text-green-primary inline mb-1" />
          <div>{t('empty_no_allergies')}</div>
        </div>
      )}
    </div>
  );
}

function Step4({ data, set }) { return <DislikedPicker data={data} set={set} kind="foods" stepKey="step4" />; }
function Step5({ data, set }) { return <DislikedPicker data={data} set={set} kind="drinks" stepKey="step5" />; }

function DislikedPicker({ data, set, kind }) {
  const t = useT();
  const { locale } = useLocale();
  const [search, setSearch] = React.useState('');
  const groups = kind === 'foods' ? window.FOODS : window.DRINKS;
  const valueKey = kind === 'foods' ? 'dislikedFoods' : 'dislikedDrinks';
  const selected = data[valueKey];
  const toggle = (it) => {
    const has = selected.includes(it);
    set({ [valueKey]: has ? selected.filter(x => x !== it) : [...selected, it] });
  };
  const visible = (cat) => groups[cat].filter(x => x.toLowerCase().includes(search.toLowerCase()));
  const stepKey = kind === 'foods' ? 'onb_step4' : 'onb_step5';
  return (
    <div className="card p-6 md:p-8 space-y-4">
      <div>
        <h2 className="h2 text-2xl mb-1">{t(stepKey)}</h2>
        <p className="text-sm text-ink/60">Selectează ce nu vrei să apară în meniul tău.</p>
      </div>
      <div className="flex items-center gap-3 flex-wrap">
        <div className="relative max-w-sm flex-1 min-w-[200px]">
          <Icon name="search" size={16} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-ink/40" />
          <Input value={search} onChange={e => setSearch(e.target.value)} placeholder={t('onb_search')} className="pl-10" />
        </div>
        <Pill tone="neutral">{t('onb_selected', selected.length)}</Pill>
      </div>
      <div className="space-y-5">
        {Object.keys(groups).map(cat => {
          const items = visible(cat);
          if (items.length === 0) return null;
          return (
            <div key={cat}>
              <div className="text-xs uppercase tracking-[0.12em] font-semibold text-olive mb-2">{window.CATEGORY_LABELS[cat][locale]}</div>
              <div className="flex flex-wrap gap-2">
                {items.map(it => {
                  const on = selected.includes(it);
                  return (
                    <button key={it} onClick={() => toggle(it)}
                      className={cls("px-3 py-1.5 rounded-full text-sm border transition-all",
                        on ? 'bg-ink text-white border-ink' : 'bg-white text-ink/75 border-sage hover:border-ink/30')}>
                      {on && <Icon name="x" size={12} className="inline mr-1" />}
                      {it}
                    </button>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function Step6({ data, set }) {
  const t = useT();
  const cats = ['hepatic', 'renal', 'tumor', 'cardiac', 'metabolic', 'hormonal', 'vitamins'];
  const [tab, setTab] = React.useState('vitamins');

  const expired = React.useMemo(() => {
    if (!data.labDate) return false;
    const d = new Date(data.labDate);
    const cutoff = new Date('2026-05-07');
    cutoff.setMonth(cutoff.getMonth() - 6);
    return d < cutoff;
  }, [data.labDate]);

  const setLab = (k, v) => set({ labValues: { ...data.labValues, [k]: v } });

  const computeStatus = (test, val) => {
    if (val === '' || val === undefined || val === null) return 'pending';
    const v = parseFloat(val);
    if (isNaN(v)) return 'pending';
    if (v < test.refMin || v > test.refMax) return 'outofrange';
    const span = test.refMax - test.refMin;
    if (v < test.refMin + span * 0.1 || v > test.refMax - span * 0.1) return 'attention';
    return 'normal';
  };

  return (
    <div className="card p-6 md:p-8 space-y-5">
      <div>
        <h2 className="h2 text-2xl mb-1">{t('onb_step6')}</h2>
        <p className="text-sm text-ink/60">Introdu valorile din analizele tale recente. Cu cât sunt mai recente, cu atât meniul e mai precis.</p>
      </div>
      <div className="flex items-end gap-4 flex-wrap">
        <Field label={t('onb_lab_date')} className="max-w-[200px]">
          <Input type="date" value={data.labDate} onChange={e => set({ labDate: e.target.value })} />
        </Field>
        <button className="border-2 border-dashed border-sage hover:border-green-primary/50 rounded-2xl px-4 py-2.5 text-sm text-ink/65 inline-flex items-center gap-2">
          <Icon name="upload" size={15} /> {t('onb_lab_upload')}
        </button>
      </div>
      {expired && (
        <div className="bg-coral/10 border border-coral/30 rounded-2xl p-4 flex items-start gap-3">
          <Icon name="alert" size={18} className="text-coral flex-shrink-0 mt-0.5" />
          <p className="text-sm text-ink/80">{t('onb_lab_expired')}</p>
        </div>
      )}
      <Tabs value={tab} onChange={setTab} options={cats.map(c => ({ value: c, label: t(`lab_${c}`) }))} />
      <div className="overflow-x-auto -mx-2 px-2">
        <table className="w-full text-sm">
          <thead>
            <tr className="text-xs uppercase tracking-[0.1em] text-ink/55 text-left">
              <th className="py-2 pr-4 font-semibold">Marker</th>
              <th className="py-2 pr-4 font-semibold">Valoare</th>
              <th className="py-2 pr-4 font-semibold">Unitate</th>
              <th className="py-2 pr-4 font-semibold">Interval</th>
              <th className="py-2 font-semibold">Status</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-sage">
            {window.LAB_TESTS[tab].map(test => {
              const val = data.labValues[test.key] ?? '';
              const status = computeStatus(test, val);
              return (
                <tr key={test.key}>
                  <td className="py-3 pr-4 font-medium text-ink">{test.name}</td>
                  <td className="py-2 pr-4"><Input type="number" step="0.1" value={val} onChange={e => setLab(test.key, e.target.value)} className="!py-2 !text-sm max-w-[120px]" /></td>
                  <td className="py-3 pr-4 text-ink/55 text-xs">{test.unit}</td>
                  <td className="py-3 pr-4 text-ink/55 text-xs">{test.refMin}–{test.refMax}</td>
                  <td className="py-3"><StatusPill status={status} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function Step7({ data, set }) {
  const t = useT();
  const cats = ['anxiety', 'stress', 'sleep', 'energy', 'mood'];
  const setAns = (cat, qi, v) => {
    const cur = data.psych[cat] || {};
    set({ psych: { ...data.psych, [cat]: { ...cur, [`q${qi}`]: v } } });
  };
  const totalFor = (cat) => {
    const a = data.psych[cat] || {};
    return Object.values(a).reduce((s, v) => s + Number(v || 0), 0);
  };
  const allDone = cats.every(c => Object.keys(data.psych[c] || {}).length === 3);

  // recharts radar
  const RC = window.Recharts || {};
  const RadarChart = RC.RadarChart, PolarGrid = RC.PolarGrid, PolarAngleAxis = RC.PolarAngleAxis,
    Radar = RC.Radar, ResponsiveContainer = RC.ResponsiveContainer, PolarRadiusAxis = RC.PolarRadiusAxis;
  const radarData = cats.map(c => ({ category: t(`cat_${c}`), value: totalFor(c) }));

  return (
    <div className="card p-6 md:p-8 space-y-6">
      <div>
        <h2 className="h2 text-2xl mb-1">{t('onb_step7')}</h2>
        <p className="text-sm text-ink/60">3 întrebări per categorie. Acest pas ne ajută să adaptăm meniul la starea ta.</p>
      </div>
      {cats.map(cat => (
        <div key={cat} className="border border-sage rounded-2xl p-5">
          <div className="flex items-center justify-between mb-3">
            <div className="serif text-lg font-semibold text-purple-primary">{t(`cat_${cat}`)}</div>
            <Pill tone="purple">{t('onb_psych_running')}: {totalFor(cat)} / 9</Pill>
          </div>
          <div className="space-y-4">
            {window.PSYCH_QUESTIONS[cat].map((q, qi) => (
              <div key={qi}>
                <div className="text-sm text-ink/85 mb-2">{q}</div>
                <div className="flex flex-wrap gap-2">
                  {t('onb_psych_options').map((label, opi) => {
                    const sel = (data.psych[cat] || {})[`q${qi}`] === opi;
                    return (
                      <button key={opi} onClick={() => setAns(cat, qi, opi)}
                        className={cls("px-3 py-2 rounded-full text-xs border-2 transition-all",
                          sel ? 'bg-purple-primary text-white border-purple-primary' : 'bg-white border-sage hover:border-purple-primary/40 text-ink/70')}>
                        {label}
                      </button>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>
        </div>
      ))}
      {allDone && RadarChart && (
        <div className="bg-sage/40 rounded-2xl p-5">
          <div className="text-sm font-semibold mb-2">Profilul tău</div>
          <div className="h-64">
            <ResponsiveContainer width="100%" height="100%">
              <RadarChart data={radarData}>
                <PolarGrid stroke="#CFD4BE" />
                <PolarAngleAxis dataKey="category" tick={{ fontSize: 11, fill: '#212529' }} />
                <PolarRadiusAxis domain={[0, 9]} tick={{ fontSize: 10, fill: '#999' }} />
                <Radar dataKey="value" stroke="#662D91" fill="#662D91" fillOpacity={0.35} />
              </RadarChart>
            </ResponsiveContainer>
          </div>
        </div>
      )}
    </div>
  );
}

function OnboardingCompletePage() {
  const t = useT();
  const { setDemoMode } = useApp();
  React.useEffect(() => { setDemoMode('first_menu'); }, []);
  return (
    <div className="min-h-[calc(100vh-4rem)] flex items-center justify-center px-4 relative overflow-hidden">
      <Blob color="#95C500" x="-200px" y="-200px" size={500} opacity={0.2} />
      <Blob color="#A874A8" x="auto" y="auto" size={500} opacity={0.18} className="!right-[-200px] !bottom-[-200px] !top-auto !left-auto" />
      <div className="text-center max-w-md relative">
        <div className="mx-auto w-32 h-32 rounded-full bg-lime/30 flex items-center justify-center mb-6 relative">
          <div className="absolute inset-2 rounded-full bg-lime/50" />
          <Icon name="leaf" size={48} className="text-green-primary relative" />
        </div>
        <h1 className="h1 text-4xl mb-3">{t('onb_complete_title')}</h1>
        <p className="text-ink/65 mb-8">{t('onb_complete_sub')}</p>
        <Button variant="primary" onClick={() => navigate('/account')}>
          {t('onb_complete_cta')}
          <Icon name="arrow_right" size={14} />
        </Button>
      </div>
    </div>
  );
}

Object.assign(window, { OnboardingPage, OnboardingCompletePage });
// Client account: Dashboard, Menu viewer, Renewal, Settings, Billing, Subscription mgmt

function AccountDashboardPage() {
  const t = useT();
  const { demoMode, ana, validations, subscription, setSubscription } = useApp();
  const isWaiting = demoMode === 'first_menu';
  const isFresh = demoMode === 'fresh_purchase';
  const labsExpired = demoMode === 'labs_expired';
  const [labModalOpen, setLabModalOpen] = React.useState(false);
  const [reminderDismissed, setReminderDismissed] = React.useState(false);

  // Compute soonest expiring validation for banner
  const soonExpiring = React.useMemo(() => {
    return Object.entries(validations).find(([k, v]) => v.daysToExpire >= 0 && v.daysToExpire < 30 && v.status !== 'expired');
  }, [validations]);

  const onRenew = (e) => {
    if (labsExpired) { e?.preventDefault(); setLabModalOpen(true); return; }
    navigate('/account/renew');
  };

  // Fresh purchase — form not filled at all
  if (isFresh) {
    return (
      <div className="min-h-[calc(100vh-4rem)] bg-cream pb-16">
        <div className="max-w-4xl mx-auto px-4 md:px-8 py-8">
          <div className="card overflow-hidden relative">
            <Blob color="#95C500" x="auto" y="-100px" size={320} opacity={0.18} className="!right-[-50px] !left-auto" />
            <div className="p-8 md:p-12 relative">
              <div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-green-primary/10 text-green-primary text-xs font-semibold uppercase tracking-[0.12em] mb-4">
                <Icon name="check" size={12} strokeWidth={3} /> Pachet activat
              </div>
              <h1 className="h1 text-3xl md:text-4xl mb-3">Bun-venit, {ana.firstName}!</h1>
              <p className="text-ink/70 max-w-xl mb-6 text-base md:text-lg">
                Plata pentru <strong>{subscription.planName}</strong> a fost confirmată. Pentru a începe, completează formularul medical — durează ~10 minute și ne ajută să-ți construim primul meniu personalizat.
              </p>
              <div className="grid sm:grid-cols-3 gap-3 mb-7">
                {[
                  { n: 1, label: 'Date personale & obiective' },
                  { n: 2, label: 'Analize medicale' },
                  { n: 3, label: 'Test psihologic & preferințe' },
                ].map(s => (
                  <div key={s.n} className="rounded-2xl border border-sage bg-white p-4">
                    <div className="text-xs text-ink/55 mb-1">Pas {s.n}</div>
                    <div className="text-sm font-medium text-ink">{s.label}</div>
                  </div>
                ))}
              </div>
              <div className="flex items-center gap-3 flex-wrap">
                <Button variant="primary" onClick={() => navigate('/onboarding')}>
                  <Icon name="arrow_right" size={14} /> Începe formularul
                </Button>
                <Button variant="outline" onClick={() => navigate('/account/settings')}>Setări cont</Button>
              </div>
              <div className="text-xs text-ink/45 mt-5">Poți reveni oricând — răspunsurile se salvează automat.</div>
            </div>
          </div>

          <div className="grid sm:grid-cols-3 gap-3 mt-6">
            <div className="card p-4">
              <div className="text-xs uppercase tracking-[0.12em] text-olive font-semibold mb-1">Pachet</div>
              <div className="text-sm font-semibold text-ink">{subscription.planName}</div>
              <div className="text-xs text-ink/55 mt-0.5">{subscription.totalMenus} meniuri</div>
            </div>
            <div className="card p-4">
              <div className="text-xs uppercase tracking-[0.12em] text-olive font-semibold mb-1">Status formular</div>
              <Pill tone="beige">Necompletat</Pill>
            </div>
            <div className="card p-4">
              <div className="text-xs uppercase tracking-[0.12em] text-olive font-semibold mb-1">Primul meniu</div>
              <div className="text-sm font-semibold text-ink">După formular</div>
              <div className="text-xs text-ink/55 mt-0.5">~24h după trimitere</div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-[calc(100vh-4rem)] bg-cream pb-16">
      <div className="max-w-6xl mx-auto px-4 md:px-8 py-8">
        {/* Reminder banner */}
        {!isWaiting && !reminderDismissed && soonExpiring && (
          <div className="bg-warm-beige border border-purple-primary/20 rounded-2xl p-4 mb-6 flex items-center gap-3 flex-wrap">
            <Icon name="alert" size={18} className="text-purple-primary" />
            <div className="flex-1 text-sm text-ink/80">{t('dash_reminder_banner', soonExpiring[1].daysToExpire)}</div>
            <Button size="sm" variant="primary" onClick={() => navigate('/onboarding?step=2')}>{t('dash_update')}</Button>
            <button onClick={() => setReminderDismissed(true)} className="text-ink/55 hover:text-ink p-1">
              <Icon name="x" size={16} />
            </button>
          </div>
        )}

        {/* Hero card */}
        <div className="card overflow-hidden mb-6 relative">
          <Blob color="#95C500" x="auto" y="-100px" size={300} opacity={0.18} className="!right-[-50px] !left-auto" />
          <div className="grid md:grid-cols-[1fr_240px] relative">
            <div className="p-6 md:p-8">
              <div className="text-xs uppercase tracking-[0.14em] text-olive font-semibold mb-2">{t('dash_hello_label')}</div>
              <h1 className="h1 text-3xl md:text-4xl mb-2">
                {isWaiting ? t('dash_hi_first', ana.firstName) : t('dash_hi', ana.firstName)}
              </h1>
              <p className="text-ink/65 mb-5 max-w-lg">
                {isWaiting ? t('dash_first_helper') : t('dash_active_helper', 11)}
              </p>
              {isWaiting ? (
                <div className="flex items-center gap-2 flex-wrap">
                  {[
                    { label: t('dash_status_data'), done: true },
                    { label: t('dash_status_gen'), active: true },
                    { label: t('dash_status_email') },
                    { label: t('dash_status_app') },
                  ].map((s, i) => (
                    <React.Fragment key={i}>
                      <div className={cls("inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-medium",
                        s.done ? 'bg-green-primary text-white' : s.active ? 'bg-purple-primary text-white' : 'bg-sage text-ink/60')}>
                        {s.done && <Icon name="check" size={12} strokeWidth={3} />}
                        {s.active && <span className="inline-block w-1.5 h-1.5 rounded-full bg-white animate-pulse" />}
                        {s.label}
                      </div>
                      {i < 3 && <div className="text-ink/30 hidden md:block">→</div>}
                    </React.Fragment>
                  ))}
                </div>
              ) : (
                <div className="flex items-center gap-3 flex-wrap">
                  <Button variant="primary" onClick={() => navigate('/account/menu/3')}>{t('dash_view_menu')}</Button>
                  <Button variant="outline" onClick={() => navigate('/account/settings')}>{t('dash_settings')}</Button>
                </div>
              )}
            </div>
            <div className="hidden md:block">
              <FoodImage kind="bowl" size="lg" className="!h-full" />
            </div>
          </div>
        </div>

        {/* Three column grid */}
        <div className="grid lg:grid-cols-3 gap-5">
          <SubscriptionCard subscription={subscription} onRenew={onRenew} labsExpired={labsExpired} />
          <ValidationsCard validations={validations} />
          <NextDeliveryCard isWaiting={isWaiting} />
        </div>

        {/* Menu history */}
        <div className="mt-8">
          <div className="flex items-center justify-between mb-3">
            <h2 className="serif text-2xl font-semibold text-purple-primary">{t('dash_menu_history')}</h2>
          </div>
          {isWaiting ? (
            <div className="card p-10 text-center">
              <div className="mx-auto w-16 h-16 rounded-full bg-sage flex items-center justify-center mb-3">
                <Icon name="leaf" size={28} className="text-green-primary" />
              </div>
              <div className="text-ink/65">{t('dash_empty_menu')}</div>
            </div>
          ) : (
            <div className="card overflow-hidden">
              <table className="w-full text-sm">
                <thead className="text-xs uppercase tracking-[0.1em] text-ink/55 bg-cream">
                  <tr>
                    <th className="text-left p-3 font-semibold">{t('dash_th_week')}</th>
                    <th className="text-left p-3 font-semibold">{t('dash_th_period')}</th>
                    <th className="text-left p-3 font-semibold">{t('dash_th_status')}</th>
                    <th className="text-right p-3 font-semibold">{t('dash_th_actions')}</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-sage">
                  {[
                    { id: 1, week: 1, period: '20 apr – 26 apr 2026', status: 'delivered' },
                    { id: 2, week: 2, period: '04 mai – 10 mai 2026', status: 'delivered' },
                    { id: 3, week: 3, period: '18 mai – 24 mai 2026', status: 'pending' },
                  ].map(m => (
                    <tr key={m.id} className="hover:bg-cream/60">
                      <td className="p-3 font-medium">{t('menu_week', m.week)}</td>
                      <td className="p-3 text-ink/65">{m.period}</td>
                      <td className="p-3"><Pill tone={m.status === 'delivered' ? 'green' : 'beige'}>{m.status === 'delivered' ? t('status_delivered') : t('status_generating')}</Pill></td>
                      <td className="p-3 text-right">
                        {m.status === 'delivered' ? (
                          <div className="inline-flex gap-2">
                            <Button size="sm" variant="ghost" onClick={() => navigate(`/account/menu/${m.id}`)}><Icon name="eye" size={14} /> {t('dash_view')}</Button>
                            <Button size="sm" variant="ghost"><Icon name="download" size={14} /> PDF</Button>
                          </div>
                        ) : (
                          <Pill tone="beige">{t('status_generating_short')}</Pill>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>

      <Modal open={labModalOpen} onClose={() => setLabModalOpen(false)} size="md"
        footer={<>
          <Button variant="outline" onClick={() => setLabModalOpen(false)}>{t('lab_block_later')}</Button>
          <Button variant="primary" onClick={() => { setLabModalOpen(false); navigate('/onboarding?step=6'); }}>{t('lab_block_cta')}</Button>
        </>}>
        <div className="bg-coral/10 border border-coral/30 rounded-2xl p-4 mb-3 flex gap-3">
          <Icon name="alert" size={20} className="text-coral flex-shrink-0 mt-0.5" />
          <div>
            <div className="font-semibold text-coral mb-1">{t('lab_block_title')}</div>
            <p className="text-sm text-ink/80">{t('lab_block_body')}</p>
          </div>
        </div>
      </Modal>
    </div>
  );
}

function SubscriptionCard({ subscription, onRenew, labsExpired }) {
  const t = useT();
  const completed = subscription.status === 'completed';
  const paused = subscription.status === 'paused';
  const cancelled = subscription.status === 'cancelled';
  const progress = (subscription.menusDelivered / subscription.totalMenus) * 100;
  const renewDisabled = !completed && !cancelled;

  return (
    <div className="card p-5 relative">
      <div className="flex items-center justify-between mb-3">
        <div className="text-xs uppercase tracking-[0.12em] text-olive font-semibold">{t('dash_subscription')}</div>
        {paused && <Pill tone="beige">{t('status_paused')}</Pill>}
        {cancelled && <Pill tone="coral">{t('status_cancelled')}</Pill>}
      </div>
      <div className="serif text-xl font-semibold text-ink mb-2">{subscription.planName}</div>
      <div className="flex items-baseline gap-1 mb-1">
        <span className="text-2xl font-bold text-green-primary">{subscription.menusDelivered}</span>
        <span className="text-ink/55 text-sm">/ {subscription.totalMenus} {t('meals')}</span>
      </div>
      <Progress value={subscription.menusDelivered} max={subscription.totalMenus} className="mt-3 mb-3" />
      <div className="text-xs text-ink/55 mb-4">{t('val_valid_until', subscription.endDate)}</div>
      <Tooltip text={renewDisabled ? t('dash_renew_disabled_tip') : ''}>
        <div>
          <Button variant={renewDisabled ? 'outline' : 'primary'} size="sm" onClick={onRenew} disabled={renewDisabled} className="w-full">
            {labsExpired && <Icon name="alert" size={13} />}
            {t('dash_renew')}
          </Button>
        </div>
      </Tooltip>
    </div>
  );
}

function ValidationsCard({ validations }) {
  const t = useT();
  const items = [
    { key: 'labTests', label: t('val_lab') },
    { key: 'psychAssessment', label: t('val_psych') },
    { key: 'allergies', label: t('val_allergies') },
    { key: 'preferences', label: t('val_prefs') },
  ];
  const goEdit = (k) => {
    const stepMap = { labTests: 6, psychAssessment: 7, allergies: 3, preferences: 2 };
    navigate(`/onboarding?step=${stepMap[k]}`);
  };
  return (
    <div className="card p-5">
      <div className="text-xs uppercase tracking-[0.12em] text-olive font-semibold mb-3">{t('dash_validations')}</div>
      <div className="space-y-2.5">
        {items.map(it => {
          const v = validations[it.key];
          const expired = v.status === 'expired';
          const expiring = v.daysToExpire < 30 && v.daysToExpire >= 0;
          return (
            <div key={it.key} className="flex items-center justify-between gap-2">
              <div className="text-sm font-medium text-ink">{it.label}</div>
              <div className="flex items-center gap-2">
                {expired ? <Pill tone="coral">{t('val_expired')}</Pill>
                  : expiring ? <Pill tone="beige">{t('val_expiring', v.daysToExpire)}</Pill>
                  : <Pill tone="green">{t('val_valid_until', v.nextRequiredUpdateDate)}</Pill>}
                {(expired || expiring) && (
                  <button onClick={() => goEdit(it.key)} className="text-olive hover:underline text-xs font-medium">{t('val_update')}</button>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function NextDeliveryCard({ isWaiting }) {
  const t = useT();
  return (
    <div className="card p-5 bg-warm-beige/40 border-warm-beige relative overflow-hidden">
      <div className="text-xs uppercase tracking-[0.12em] text-olive font-semibold mb-3 relative">{t('dash_next_delivery')}</div>
      {isWaiting ? (
        <>
          <div className="serif text-xl font-semibold text-ink mb-1">~ {t('dash_in', '1–2')}</div>
          <div className="text-xs text-ink/55">{t('dash_first_eta')}</div>
        </>
      ) : (
        <>
          <div className="serif text-2xl font-semibold text-ink mb-1">18 mai 2026</div>
          <div className="text-sm text-ink/55 mb-4">{t('menu_week', 3)} · 7 {t('days')}</div>
          <Pill tone="purple">{t('status_scheduled')}</Pill>
        </>
      )}
    </div>
  );
}

// ---------- MENU VIEWER ----------

function MenuViewerPage({ params = {} }) {
  const t = useT();
  const { menuId } = params;
  const [day, setDay] = React.useState(0);
  const [acceptOpen, setAcceptOpen] = React.useState(false);
  const [accepted, setAccepted] = React.useState(false);
  const [pdfOpen, setPdfOpen] = React.useState(false);
  const [emailOpen, setEmailOpen] = React.useState(false);

  React.useEffect(() => {
    const flag = localStorage.getItem('account.firstMenuAccepted');
    if (!flag) setAcceptOpen(true);
  }, []);

  const days = ['Luni', 'Marți', 'Miercuri', 'Joi', 'Vineri', 'Sâmbătă', 'Duminică'];
  const menu = { meals: window.ANA_WEEK[day] || [] };
  const totalKcal = menu.meals.reduce((s, m) => s + m.kcal, 0);

  return (
    <div className="min-h-[calc(100vh-4rem)] bg-cream pb-16">
      <div className="max-w-5xl mx-auto px-4 md:px-8 py-8">
        {/* Top */}
        <div className="flex items-center justify-between mb-5 flex-wrap gap-3">
          <div>
            <button onClick={() => navigate('/account')} className="text-olive hover:underline text-sm inline-flex items-center gap-1 mb-2">
              <Icon name="arrow_left" size={13} /> {t('back_to_dashboard')}
            </button>
            <h1 className="h1 text-3xl">{t('menu_week', menuId)} <span className="text-ink/55 font-normal">· {t('menu_for', 'Ana Popescu')}</span></h1>
          </div>
          <div className="flex items-center gap-2">
            <Button variant="ghost" size="sm" onClick={() => setEmailOpen(true)}><Icon name="mail" size={14} /> {t('menu_send_email')}</Button>
            <Button variant="primary" size="sm" onClick={() => setPdfOpen(true)}><Icon name="download" size={14} /> {t('menu_download')}</Button>
          </div>
        </div>

        {/* Day tabs */}
        <div className="card p-2 mb-5 overflow-x-auto">
          <div className="flex gap-1 min-w-max">
            {days.map((d, i) => (
              <button key={i} onClick={() => setDay(i)}
                className={cls("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap",
                  day === i ? 'bg-green-primary text-white' : 'text-ink/70 hover:bg-sage')}>
                {d}
              </button>
            ))}
          </div>
        </div>

        {/* Day stats */}
        <div className="grid md:grid-cols-[1fr_280px] gap-5 mb-6">
          <div className="card p-5 flex items-center justify-between bg-green-primary text-white relative overflow-hidden">
            <Blob color="#95C500" x="auto" y="auto" size={300} opacity={0.3} className="!right-[-100px] !top-[-50px] !left-auto" />
            <div className="relative">
              <div className="text-xs uppercase tracking-[0.14em] text-white/75 font-semibold mb-1">{t('menu_total_day')}</div>
              <div className="serif text-4xl font-semibold">{totalKcal} <span className="text-base text-white/75 font-sans font-medium">kcal</span></div>
            </div>
            <div className="text-right relative">
              <div className="text-xs uppercase tracking-[0.14em] text-white/60 font-semibold">{days[day]}</div>
              <div className="text-2xl serif font-semibold">{menu.meals.length} {t('meals')}</div>
            </div>
          </div>
          <MacrosCard />
        </div>

        {/* Meals */}
        <div className="space-y-4">
          {menu.meals.map((meal, i) => <MealCard key={i} meal={meal} />)}
        </div>
      </div>

      {/* First-menu acceptance modal */}
      <Modal open={acceptOpen} onClose={() => {}} size="md"
        title={t('menu_accept_title')}
        showClose={false}
        footer={
          <Button variant="primary" disabled={!accepted} onClick={() => {
            localStorage.setItem('account.firstMenuAccepted', '1');
            setAcceptOpen(false);
          }}>{t('menu_accept_continue')}</Button>
        }>
        <div className="bg-coral/10 border border-coral/30 rounded-2xl p-4 mb-4 flex gap-3">
          <Icon name="alert" size={18} className="text-coral flex-shrink-0 mt-0.5" />
          <p className="text-sm text-ink/80">{t('terms_disclaimer')}</p>
        </div>
        <Checkbox checked={accepted} onChange={setAccepted} label={t('menu_accept_check')} />
      </Modal>

      <Modal open={pdfOpen} onClose={() => setPdfOpen(false)} size="lg" title="PDF preview">
        <PDFPreview menu={menu} day={days[day]} />
      </Modal>
      <Modal open={emailOpen} onClose={() => setEmailOpen(false)} size="md" title={t('menu_send_email')}>
        <p className="text-sm text-ink/65 mb-4">{t('menu_send_helper', 'ana.popescu@example.com')}</p>
        <Button variant="primary" onClick={() => { setEmailOpen(false); window.toast?.push(t('menu_sent')); }}>{t('menu_send_btn')}</Button>
      </Modal>
    </div>
  );
}

function MealCard({ meal }) {
  const t = useT();
  return (
    <div className="card p-5 md:p-6">
      <div className="flex items-center justify-between mb-4 pb-3 border-b border-sage">
        <div>
          <div className="text-xs uppercase tracking-[0.12em] text-olive font-semibold mb-1">{meal.time}</div>
          <h3 className="serif text-xl font-semibold text-ink">{t(`meal_${meal.mealType}`)}</h3>
        </div>
        <div className="text-right">
          <div className="text-2xl serif font-semibold text-green-primary">{meal.kcal}</div>
          <div className="text-xs text-ink/55 -mt-0.5">kcal</div>
        </div>
      </div>
      <div className="space-y-3">
        {meal.items.map((it, i) => (
          <div key={i} className="flex items-start gap-3">
            <div className="w-9 h-9 rounded-full bg-sage flex-shrink-0 flex items-center justify-center text-green-primary">
              <Icon name="leaf" size={14} />
            </div>
            <div className="flex-1 min-w-0">
              <div className="font-medium text-ink text-sm">{it.food}</div>
              <div className="text-xs text-ink/55">{it.amount}{it.kcal ? ` · ${it.kcal} kcal` : ''}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function MacrosCard() {
  const t = useT();
  // mock macro ring
  const macros = [
    { label: t('macro_carbs'), value: 50, color: '#95C500' },
    { label: t('macro_protein'), value: 25, color: '#417A3E' },
    { label: t('macro_fat'), value: 25, color: '#662D91' },
  ];
  let acc = 0;
  return (
    <div className="card p-5">
      <div className="text-xs uppercase tracking-[0.12em] text-olive font-semibold mb-3">{t('menu_macros')}</div>
      <div className="flex items-center gap-4">
        <svg width="80" height="80" viewBox="0 0 36 36">
          <circle cx="18" cy="18" r="15.9" fill="none" stroke="#EEF1E4" strokeWidth="3.5" />
          {macros.map((m, i) => {
            const offset = -acc;
            acc += m.value;
            return (
              <circle key={i} cx="18" cy="18" r="15.9" fill="none" stroke={m.color} strokeWidth="3.5"
                strokeDasharray={`${m.value} ${100 - m.value}`} strokeDashoffset={offset}
                transform="rotate(-90 18 18)" />
            );
          })}
        </svg>
        <div className="flex-1 space-y-1">
          {macros.map((m, i) => (
            <div key={i} className="flex items-center justify-between text-xs">
              <div className="flex items-center gap-1.5">
                <span className="w-2 h-2 rounded-full" style={{ background: m.color }} />
                <span className="text-ink/70">{m.label}</span>
              </div>
              <span className="font-semibold text-ink">{m.value}%</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function PDFPreview({ menu, day }) {
  const t = useT();
  const totalKcal = menu.meals.reduce((s, m) => s + m.kcal, 0);
  return (
    <div className="bg-cream rounded-2xl p-6 max-h-[70vh] overflow-y-auto">
      <div className="bg-white shadow-md rounded-lg p-8 mx-auto" style={{ maxWidth: 595 }}>
        <div className="relative mb-6">
          <div className="absolute -top-4 -left-4 w-24 h-24 rounded-full" style={{ background: 'radial-gradient(circle, rgba(149,197,0,0.25), transparent 70%)' }} />
          <div className="relative">
            <div className="text-xs tracking-[0.18em] uppercase text-olive font-semibold">Silueta Nutrițională</div>
            <div className="serif text-3xl text-green-primary font-semibold mt-1">Meniu personalizat</div>
            <div className="text-sm text-ink/55 mt-1">Generat pe 2026-05-04 pentru Ana Popescu</div>
          </div>
        </div>
        <div className="border-t border-b border-sage py-3 mb-5 text-sm">
          <strong>{day}</strong> · Total: {totalKcal} kcal
        </div>
        {menu.meals.map((m, i) => (
          <div key={i} className="mb-4">
            <div className="font-semibold text-purple-primary serif text-lg">{m.time} · {t(`meal_${m.mealType}`)}</div>
            <ul className="ml-5 mt-1 list-disc text-sm text-ink/75 space-y-0.5">
              {m.items.map((it, j) => <li key={j}>{it.food} <span className="text-ink/45">({it.amount})</span></li>)}
            </ul>
          </div>
        ))}
        <div className="mt-8 pt-4 border-t border-sage">
          <div className="text-[9px] uppercase tracking-[0.14em] text-ink/45 font-semibold mb-1">{t('terms_disclaimer_title')}</div>
          <p className="text-[10px] text-ink/55 leading-snug mb-3">{t('terms_disclaimer')}</p>
          <div className="text-center text-xs text-ink/40">Pagina 1 din 7</div>
        </div>
      </div>
    </div>
  );
}

// ---------- RENEWAL ----------

function RenewalPage() {
  const t = useT();
  const { ana, validations } = useApp();
  const expired = Object.entries(validations).filter(([, v]) => v.status === 'expired');
  const valid = Object.entries(validations).filter(([, v]) => v.status === 'valid');

  return (
    <div className="min-h-[calc(100vh-4rem)] bg-cream pb-16">
      <div className="max-w-5xl mx-auto px-4 md:px-8 py-8">
        <div className="card p-6 md:p-8 mb-6 relative overflow-hidden">
          <Blob color="#95C500" x="auto" y="auto" size={300} opacity={0.18} className="!right-[-100px] !top-[-100px] !left-auto" />
          <div className="relative">
            <div className="text-xs uppercase tracking-[0.14em] text-olive font-semibold mb-2">{t('renew_welcome_back', ana.firstName)}</div>
            <h1 className="h1 text-3xl md:text-4xl mb-2">{t('renew_title', ana.firstName)}</h1>
            <p className="text-ink/65 max-w-lg">{t('renew_sub')}</p>
          </div>
        </div>

        <div className="grid md:grid-cols-2 gap-5 mb-8">
          <div className="card p-5">
            <div className="text-xs uppercase tracking-[0.12em] text-olive font-semibold mb-3 flex items-center gap-2">
              <Icon name="check" size={14} className="text-green-primary" strokeWidth={2.4} />
              {t('renew_valid_data')}
            </div>
            <ul className="space-y-2 text-sm">
              {valid.map(([k]) => (
                <li key={k} className="flex items-center gap-2">
                  <Icon name="check" size={14} className="text-green-primary" strokeWidth={2.5} />
                  <span>{t(`val_${k === 'labTests' ? 'lab' : k === 'psychAssessment' ? 'psych' : k}`)}</span>
                </li>
              ))}
            </ul>
          </div>
          {expired.length > 0 && (
            <div className="card p-5 border-coral/30 bg-coral/5">
              <div className="text-xs uppercase tracking-[0.12em] text-coral font-semibold mb-3 flex items-center gap-2">
                <Icon name="alert" size={14} className="text-coral" />
                {t('renew_to_update')}
              </div>
              <div className="space-y-2">
                {expired.map(([k]) => (
                  <div key={k} className="flex items-center justify-between text-sm">
                    <span>{t(`val_${k === 'labTests' ? 'lab' : k === 'psychAssessment' ? 'psych' : k}`)}</span>
                    <Button size="sm" variant="ghost" onClick={() => navigate('/onboarding?step=' + (k === 'labTests' ? 6 : 7))}>
                      <Icon name="edit" size={13} /> {t('renew_fix')}
                    </Button>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        <PlansGrid renewMode />
      </div>
    </div>
  );
}

// ---------- SETTINGS ----------

function SettingsPage() {
  const t = useT();
  const { locale, setLocale } = useLocale();
  const { ana } = useApp();
  const [editEmail, setEditEmail] = React.useState(false);
  const [pwdOpen, setPwdOpen] = React.useState(false);

  return (
    <div className="min-h-[calc(100vh-4rem)] bg-cream pb-16">
      <div className="max-w-3xl mx-auto px-4 md:px-8 py-8">
        <h1 className="h1 text-3xl md:text-4xl mb-2">{t('set_title')}</h1>
        <p className="text-ink/55 mb-8">{t('set_sub')}</p>

        <div className="flex gap-2 mb-6 flex-wrap">
          <Button variant="outline" size="sm" onClick={() => navigate('/account/settings/billing')}><Icon name="receipt" size={14} /> {t('set_billing')}</Button>
          <Button variant="outline" size="sm" onClick={() => navigate('/account/settings/subscription')}><Icon name="package" size={14} /> {t('set_sub_mgmt')}</Button>
        </div>

        {/* Profile */}
        <div className="card p-6 mb-5">
          <h2 className="serif text-xl font-semibold text-purple-primary mb-4">{t('set_profile')}</h2>
          <div className="space-y-3 divide-y divide-sage">
            <SettingRow label={t('set_name')} value={`${ana.firstName} ${ana.lastName}`} locked />
            <SettingRow label={t('set_email')} value={ana.email} editable onEdit={() => setEditEmail(true)} />
            <SettingRow label={t('set_dob')} value={ana.dob} locked />
            <SettingRow label={t('set_sex')} value={ana.sex === 'female' ? 'Feminin' : 'Masculin'} locked />
            <SettingRow label={t('set_height')} value={`${ana.heightCm} cm`} locked />
          </div>
        </div>

        {/* Language */}
        <div className="card p-6 mb-5">
          <h2 className="serif text-xl font-semibold text-purple-primary mb-2">{t('set_language')}</h2>
          <p className="text-sm text-ink/55 mb-4">{t('set_language_helper')}</p>
          <Select value={locale} onChange={e => setLocale(e.target.value)} className="max-w-xs">
            <option value="ro">Română</option>
            <option value="en">English</option>
          </Select>
        </div>

        {/* Security */}
        <div className="card p-6">
          <h2 className="serif text-xl font-semibold text-purple-primary mb-4">{t('set_security')}</h2>
          <div className="flex flex-wrap gap-3">
            <Button variant="outline" onClick={() => setPwdOpen(true)}>{t('set_change_pwd')}</Button>
            <Button variant="ghost" onClick={() => navigate('/login')}><Icon name="logout" size={14} /> {t('set_logout')}</Button>
          </div>
        </div>
      </div>

      <Modal open={editEmail} onClose={() => setEditEmail(false)} title={t('set_change_email')} size="sm"
        footer={<><Button variant="outline" onClick={() => setEditEmail(false)}>{t('cancel')}</Button><Button variant="primary" onClick={() => setEditEmail(false)}>{t('save')}</Button></>}>
        <Field label={t('set_current_pwd')}><Input type="password" /></Field>
        <Field label={t('set_new_email')}><Input type="email" defaultValue={ana.email} /></Field>
      </Modal>

      <Modal open={pwdOpen} onClose={() => setPwdOpen(false)} title={t('set_change_pwd')} size="sm"
        footer={<><Button variant="outline" onClick={() => setPwdOpen(false)}>{t('cancel')}</Button><Button variant="primary" onClick={() => setPwdOpen(false)}>{t('save')}</Button></>}>
        <Field label={t('set_current_pwd')}><Input type="password" /></Field>
        <Field label={t('set_new_pwd')}><Input type="password" /></Field>
        <Field label={t('set_confirm_pwd')}><Input type="password" /></Field>
      </Modal>
    </div>
  );
}

function SettingRow({ label, value, locked, editable, onEdit }) {
  const t = useT();
  return (
    <div className="flex items-center justify-between py-3 first:pt-0">
      <div>
        <div className="text-xs uppercase tracking-[0.1em] text-ink/55 font-semibold">{label}</div>
        <div className="text-sm font-medium text-ink mt-0.5">{value}</div>
      </div>
      {editable ? (
        <Button variant="ghost" size="sm" onClick={onEdit}><Icon name="edit" size={13} /> {t('set_edit')}</Button>
      ) : locked ? (
        <Tooltip text={t('set_locked_tip')}>
          <Icon name="lock" size={14} className="text-ink/30" />
        </Tooltip>
      ) : null}
    </div>
  );
}

function BillingPage() {
  const t = useT();
  const [invoiceOpen, setInvoiceOpen] = React.useState(false);
  const rows = [
    { id: 'INV-2026-001', plan: 'Pachet Standard', start: '2026-04-20', end: '2026-07-13', status: 'active', amount: 1100, payment: 'paid' },
  ];
  return (
    <div className="min-h-[calc(100vh-4rem)] bg-cream pb-16">
      <div className="max-w-5xl mx-auto px-4 md:px-8 py-8">
        <button onClick={() => navigate('/account/settings')} className="text-olive text-sm mb-3 inline-flex items-center gap-1 hover:underline">
          <Icon name="arrow_left" size={13} /> {t('back')}
        </button>
        <h1 className="h1 text-3xl mb-1">{t('billing_title')}</h1>
        <p className="text-ink/55 mb-6">{t('billing_sub')}</p>
        <div className="card overflow-hidden">
          <table className="w-full text-sm">
            <thead className="text-xs uppercase tracking-[0.1em] text-ink/55 bg-cream">
              <tr>
                <th className="text-left p-3 font-semibold">{t('billing_th_plan')}</th>
                <th className="text-left p-3 font-semibold">{t('billing_th_start')}</th>
                <th className="text-left p-3 font-semibold">{t('billing_th_end')}</th>
                <th className="text-left p-3 font-semibold">{t('billing_th_status')}</th>
                <th className="text-right p-3 font-semibold">{t('billing_th_amount')}</th>
                <th className="text-left p-3 font-semibold">{t('billing_th_payment')}</th>
                <th className="text-right p-3 font-semibold">{t('billing_th_invoice')}</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-sage">
              {rows.map(r => (
                <tr key={r.id}>
                  <td className="p-3 font-medium">{r.plan}</td>
                  <td className="p-3 text-ink/65">{r.start}</td>
                  <td className="p-3 text-ink/65">{r.end}</td>
                  <td className="p-3"><Pill tone="green">{t(`status_${r.status}`)}</Pill></td>
                  <td className="p-3 text-right font-semibold">{r.amount} RON</td>
                  <td className="p-3"><Pill tone="green">{t(`pay_${r.payment}`)}</Pill></td>
                  <td className="p-3 text-right">
                    <Button size="sm" variant="ghost" onClick={() => setInvoiceOpen(true)}><Icon name="download" size={13} /> {t('billing_invoice_dl')}</Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
      <Modal open={invoiceOpen} onClose={() => setInvoiceOpen(false)} title={t('billing_invoice')} size="md">
        <div className="bg-cream rounded-2xl p-6">
          <div className="bg-white p-6 rounded-lg shadow text-sm">
            <div className="flex justify-between mb-4">
              <div>
                <div className="serif text-2xl text-green-primary font-semibold">Factură</div>
                <div className="text-ink/55 text-xs">INV-2026-001</div>
              </div>
              <div className="text-right text-xs text-ink/55">
                <div>Data: 2026-04-20</div>
                <div>Scadență: 2026-04-20</div>
              </div>
            </div>
            <div className="border-t border-b border-sage py-2 mb-3">
              <div className="flex justify-between"><span>Pachet Standard</span><span>1100 RON</span></div>
              <div className="text-xs text-ink/55">6 meniuri · 84 zile</div>
            </div>
            <div className="flex justify-between font-bold text-base"><span>Total</span><span>1100 RON</span></div>
          </div>
        </div>
      </Modal>
    </div>
  );
}

function SubscriptionMgmtPage() {
  const t = useT();
  const { subscription, setSubscription } = useApp();
  const [pauseOpen, setPauseOpen] = React.useState(false);
  const [cancelOpen, setCancelOpen] = React.useState(false);
  const [resumeDate, setResumeDate] = React.useState('2026-06-01');
  const [reason, setReason] = React.useState('');

  return (
    <div className="min-h-[calc(100vh-4rem)] bg-cream pb-16">
      <div className="max-w-3xl mx-auto px-4 md:px-8 py-8">
        <button onClick={() => navigate('/account/settings')} className="text-olive text-sm mb-3 inline-flex items-center gap-1 hover:underline">
          <Icon name="arrow_left" size={13} /> {t('back')}
        </button>
        <h1 className="h1 text-3xl mb-1">{t('sub_mgmt_title')}</h1>
        <p className="text-ink/55 mb-6">{t('sub_mgmt_sub')}</p>

        <div className="card p-6 mb-5">
          <div className="flex items-center justify-between mb-4">
            <div>
              <div className="text-xs uppercase tracking-[0.12em] text-olive font-semibold mb-1">{t('dash_subscription')}</div>
              <div className="serif text-2xl font-semibold">{subscription.planName}</div>
            </div>
            {subscription.status === 'paused' && <Pill tone="beige">{t('status_paused')}</Pill>}
            {subscription.status === 'cancelled' && <Pill tone="coral">{t('status_cancelled')}</Pill>}
            {subscription.status === 'active' && <Pill tone="green">{t('status_active')}</Pill>}
          </div>
          <Progress value={subscription.menusDelivered} max={subscription.totalMenus} />
          <div className="flex items-center justify-between mt-2 text-sm text-ink/65">
            <span>{t('dash_menus_delivered', subscription.menusDelivered, subscription.totalMenus)}</span>
            <span>{t('val_valid_until', subscription.endDate)}</span>
          </div>

          {subscription.status === 'active' && (
            <div className="flex gap-2 mt-5">
              <Button variant="outline" onClick={() => setPauseOpen(true)}><Icon name="pause" size={14} /> {t('sub_pause')}</Button>
              <Button variant="ghost" onClick={() => setCancelOpen(true)} className="!text-coral hover:!bg-coral/10">{t('sub_cancel')}</Button>
            </div>
          )}
          {subscription.status === 'paused' && (
            <Button variant="primary" className="mt-5" onClick={() => setSubscription({ ...subscription, status: 'active' })}>
              {t('sub_resume_now')}
            </Button>
          )}
        </div>

        {subscription.status === 'cancelled' && (
          <div className="bg-coral/10 border border-coral/25 rounded-2xl p-4 mb-5 text-sm text-ink/80">
            {t('sub_cancelled_banner', subscription.endDate)}
          </div>
        )}

        <button onClick={() => setSubscription({ ...subscription, status: 'active' })}
          className="text-xs text-ink/40 hover:underline">
          {t('sub_demo_reset')}
        </button>
      </div>

      <Modal open={pauseOpen} onClose={() => setPauseOpen(false)} title={t('sub_pause_title')} size="sm"
        footer={<>
          <Button variant="outline" onClick={() => setPauseOpen(false)}>{t('cancel')}</Button>
          <Button variant="primary" onClick={() => { setSubscription({ ...subscription, status: 'paused' }); setPauseOpen(false); }}>{t('sub_pause_confirm')}</Button>
        </>}>
        <p className="text-sm text-ink/65 mb-3">{t('sub_pause_helper')}</p>
        <Field label={t('sub_resume_at_label') || 'Reia la'}><Input type="date" value={resumeDate} onChange={e => setResumeDate(e.target.value)} /></Field>
      </Modal>

      <Modal open={cancelOpen} onClose={() => setCancelOpen(false)} title={t('sub_cancel_title')} size="sm"
        footer={<>
          <Button variant="outline" onClick={() => setCancelOpen(false)}>{t('cancel')}</Button>
          <Button variant="primary" onClick={() => { setSubscription({ ...subscription, status: 'cancelled' }); setCancelOpen(false); }} className="!bg-coral">{t('sub_cancel_confirm')}</Button>
        </>}>
        <div className="bg-coral/10 border border-coral/30 rounded-2xl p-3 mb-4 text-sm text-ink/80">{t('sub_cancel_warning')}</div>
        <Field label={t('sub_cancel_reason')}>
          <textarea value={reason} onChange={e => setReason(e.target.value)} rows={3}
            className="w-full px-3.5 py-2 rounded-2xl bg-white border border-sage focus:border-green-primary focus:ring-2 focus:ring-green-primary/15 text-sm outline-none resize-none" />
        </Field>
      </Modal>
    </div>
  );
}

// ---------- FAMILY PROFILE PICKER (concept stub) ----------

function ProfilesPage() {
  const t = useT();
  const profiles = [
    { id: 'ana', name: 'Ana', role: t('family_role_owner'), color: '#417A3E', bg: '#EEF1E4', initial: 'A', isOwner: true },
    { id: 'andrei', name: 'Andrei', role: t('family_role_partner'), color: '#662D91', bg: '#F1E8F1', initial: 'A' },
    { id: 'maria', name: 'Maria', role: t('family_role_child') + ' · 8 ani', color: '#95C500', bg: '#F4F6E0', initial: 'M', isMinor: true },
  ];
  const onPick = (p) => {
    if (window.toast?.push) window.toast.push(`${p.name} · demo concept — flow complet în lucru`);
  };
  return (
    <div className="min-h-[calc(100vh-4rem)] bg-cream py-12 md:py-20 px-4">
      <div className="max-w-5xl mx-auto">
        <div className="text-center mb-12">
          <Pill tone="purple" className="mb-4"><Icon name="spark" size={11} /> {t('family_soon_badge')}</Pill>
          <h1 className="h1 text-3xl md:text-4xl mb-3">{t('family_picker_title')}</h1>
          <p className="text-ink/65 max-w-2xl mx-auto">{t('family_picker_sub')}</p>
        </div>

        <div className="grid grid-cols-2 md:grid-cols-4 gap-5 md:gap-7 max-w-3xl mx-auto">
          {profiles.map(p => (
            <button key={p.id} onClick={() => onPick(p)}
              className="group flex flex-col items-center gap-3 transition-transform hover:scale-105">
              <div className="relative w-24 h-24 md:w-28 md:h-28 rounded-3xl flex items-center justify-center serif text-5xl font-semibold ring-2 ring-transparent group-hover:ring-green-primary transition"
                style={{ background: p.bg, color: p.color }}>
                {p.initial}
                {p.isOwner && (
                  <div className="absolute -top-2 -right-2 bg-green-primary text-white rounded-full p-1.5">
                    <Icon name="check" size={11} strokeWidth={3} />
                  </div>
                )}
              </div>
              <div className="text-center">
                <div className="font-semibold text-ink">{p.name}</div>
                <div className="text-[11px] text-ink/55 mt-0.5">{p.role}</div>
                {p.isOwner && <div className="text-[10px] uppercase tracking-[0.12em] text-green-primary font-bold mt-1">{t('family_owner_badge')}</div>}
                {p.isMinor && <div className="text-[10px] uppercase tracking-[0.12em] text-purple-primary font-bold mt-1">{t('family_minor_badge')}</div>}
              </div>
            </button>
          ))}
          <button onClick={() => window.toast?.push?.(t('family_demo_note'))}
            className="group flex flex-col items-center gap-3 transition-transform hover:scale-105">
            <div className="w-24 h-24 md:w-28 md:h-28 rounded-3xl flex items-center justify-center bg-white border-2 border-dashed border-sage text-ink/40 group-hover:border-green-primary group-hover:text-green-primary transition">
              <Icon name="plus" size={32} strokeWidth={2} />
            </div>
            <div className="text-center">
              <div className="font-semibold text-ink/55 text-sm">{t('family_add_profile')}</div>
            </div>
          </button>
        </div>

        <div className="mt-14 max-w-2xl mx-auto card p-5 bg-sage/40 border border-purple-primary/15">
          <div className="flex items-start gap-3">
            <Icon name="info" size={18} className="text-purple-primary flex-shrink-0 mt-0.5" />
            <p className="text-sm text-ink/75 leading-relaxed">{t('family_demo_note')}</p>
          </div>
        </div>

        <div className="text-center mt-8">
          <Button variant="ghost" onClick={() => navigate('/account')}>
            <Icon name="arrow_left" size={14} /> {t('family_back_to_account')}
          </Button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  AccountDashboardPage, MenuViewerPage, MealCard, RenewalPage,
  SettingsPage, BillingPage, SubscriptionMgmtPage, ProfilesPage
});
// Nutritionist (admin) pages

function AdminDashboardPage() {
  const t = useT();
  const { clients } = useApp();
  const expiredCount = clients.filter(c => c.validations.labTests.status === 'expired').length;

  const upcoming = [
    { id: 'd1', date: '2026-05-08', client: 'Mihai Ionescu', plan: 'Pachet Premium', status: 'scheduled' },
    { id: 'd2', date: '2026-05-09', client: 'Elena Dumitrescu', plan: 'Pachet Starter', status: 'generated' },
    { id: 'd3', date: '2026-05-11', client: 'Ana Popescu', plan: 'Pachet Standard', status: 'scheduled' },
    { id: 'd4', date: '2026-05-13', client: 'Ana Popescu', plan: 'Pachet Standard', status: 'scheduled' },
    { id: 'd5', date: '2026-05-15', client: 'Mihai Ionescu', plan: 'Pachet Premium', status: 'scheduled' },
  ];
  const warnings = clients.filter(c => c.validations.labTests.status !== 'valid' || c.validations.preferences.daysToExpire < 30);

  return (
    <div className="min-h-[calc(100vh-4rem)] bg-cream pb-16">
      <div className="max-w-7xl mx-auto px-4 md:px-8 py-8">
        <div className="flex items-center justify-between mb-6 flex-wrap gap-3">
          <div>
            <Pill tone="purple" className="mb-2">Nutriționist</Pill>
            <h1 className="h1 text-3xl md:text-4xl">{t('adm_dash_title')}</h1>
            <p className="text-ink/55 mt-1">{t('adm_dash_sub')}</p>
          </div>
        </div>

        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
          <KpiTile label={t('adm_kpi_clients')} value="12" icon="users" tone="green" />
          <KpiTile label={t('adm_kpi_subs')} value="10" icon="package" tone="purple" />
          <KpiTile label={t('adm_kpi_menus')} value="5" icon="calendar" tone="beige" />
          <KpiTile label={t('adm_kpi_expired')} value={expiredCount + ''} icon="alert" tone="coral" onClick={() => navigate('/admin/clients?filter=expired')} />
        </div>

        <div className="grid lg:grid-cols-2 gap-6">
          <div className="card p-5">
            <div className="flex items-center justify-between mb-4">
              <h2 className="serif text-xl font-semibold text-purple-primary">{t('adm_upcoming')}</h2>
              <Button size="sm" variant="ghost" onClick={() => navigate('/admin/menus')}>{t('adm_see_all')} <Icon name="arrow_right" size={13} /></Button>
            </div>
            <div className="divide-y divide-sage">
              {upcoming.map(d => (
                <div key={d.id} className="py-3 flex items-center gap-3">
                  <div className="w-12 h-12 rounded-xl bg-sage flex flex-col items-center justify-center text-green-primary">
                    <div className="text-[10px] uppercase font-semibold">{d.date.slice(5, 7) === '05' ? 'mai' : 'iun'}</div>
                    <div className="text-base font-bold leading-none">{d.date.slice(8, 10)}</div>
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="font-medium text-sm">{d.client}</div>
                    <div className="text-xs text-ink/55">{d.plan}</div>
                  </div>
                  <Pill tone={d.status === 'scheduled' ? 'beige' : 'green'}>{t(`adm_status_${d.status}`)}</Pill>
                  <button className="text-olive text-xs hover:underline ml-1" onClick={() => navigate('/admin/clients/ana')}>{t('adm_view')}</button>
                </div>
              ))}
            </div>
          </div>

          <div className="card p-5">
            <h2 className="serif text-xl font-semibold text-purple-primary mb-4">{t('adm_warnings')}</h2>
            {warnings.length === 0 ? (
              <div className="border-2 border-dashed border-sage rounded-2xl p-6 text-center">
                <Icon name="leaf" size={24} className="text-green-primary mx-auto mb-1" />
                <div className="text-sm text-ink/55">{t('adm_no_warnings')}</div>
              </div>
            ) : (
              <div className="space-y-2.5">
                {warnings.map(c => (
                  <div key={c.id} onClick={() => navigate(`/admin/clients/${c.id}`)}
                    className="flex items-center gap-3 py-2.5 px-3 rounded-2xl hover:bg-cream cursor-pointer">
                    <Avatar name={c.firstName + ' ' + c.lastName} size={36} />
                    <div className="flex-1 min-w-0">
                      <div className="font-medium text-sm">{c.firstName} {c.lastName}</div>
                      <div className="text-xs text-ink/55">{c.plan}</div>
                    </div>
                    {c.validations.labTests.status === 'expired'
                      ? <Pill tone="coral">{t('val_lab_expired')}</Pill>
                      : <Pill tone="beige">{t('val_expiring', c.validations.preferences.daysToExpire)}</Pill>}
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function KpiTile({ label, value, icon, tone, onClick }) {
  const palette = {
    green: 'bg-green-primary text-white',
    purple: 'bg-purple-primary text-white',
    beige: 'bg-warm-beige text-ink',
    coral: 'bg-coral text-white',
  };
  return (
    <button onClick={onClick} className={cls("card p-5 text-left transition-all", palette[tone], onClick && 'cursor-pointer hover:scale-[1.02]')}>
      <Icon name={icon} size={22} className="mb-3 opacity-80" />
      <div className="serif text-3xl font-semibold leading-none">{value}</div>
      <div className="text-xs mt-2 opacity-80 leading-tight">{label}</div>
    </button>
  );
}

function AdminClientsPage() {
  const t = useT();
  const { clients } = useApp();
  const [filter, setFilter] = React.useState('all');
  const [search, setSearch] = React.useState('');

  const filtered = clients.filter(c => {
    if (filter === 'active' && c.subscription?.status !== 'active') return false;
    if (filter === 'expired' && c.validations.labTests.status !== 'expired') return false;
    if (filter === 'paused' && c.subscription?.status !== 'paused') return false;
    if (search && !`${c.firstName} ${c.lastName} ${c.email}`.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  return (
    <div className="min-h-[calc(100vh-4rem)] bg-cream pb-16">
      <div className="max-w-7xl mx-auto px-4 md:px-8 py-8">
        <div className="flex items-center justify-between mb-6 flex-wrap gap-3">
          <div>
            <h1 className="h1 text-3xl">{t('adm_clients')}</h1>
            <p className="text-ink/55">{t('adm_clients_count', filtered.length)}</p>
          </div>
          <div className="relative max-w-xs flex-1 min-w-[220px]">
            <Icon name="search" size={16} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-ink/40" />
            <Input value={search} onChange={e => setSearch(e.target.value)} placeholder={t('adm_search_clients')} className="pl-10" />
          </div>
        </div>

        <div className="flex gap-2 mb-5 overflow-x-auto">
          {[['all', t('filter_all')], ['active', t('filter_active')], ['expired', t('filter_expired')], ['paused', t('filter_paused')]].map(([v, lbl]) => (
            <button key={v} onClick={() => setFilter(v)}
              className={cls("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap border",
                filter === v ? 'bg-purple-primary text-white border-purple-primary' : 'bg-white border-sage text-ink/70 hover:border-purple-primary/40')}>
              {lbl}
            </button>
          ))}
        </div>

        <div className="card overflow-hidden">
          <table className="w-full text-sm">
            <thead className="text-xs uppercase tracking-[0.1em] text-ink/55 bg-cream">
              <tr>
                <th className="text-left p-3 font-semibold">{t('adm_th_name')}</th>
                <th className="text-left p-3 font-semibold">{t('adm_th_plan')}</th>
                <th className="text-left p-3 font-semibold">{t('adm_th_remaining')}</th>
                <th className="text-left p-3 font-semibold">{t('adm_th_validation')}</th>
                <th className="text-left p-3 font-semibold">{t('adm_th_last_menu')}</th>
                <th className="text-left p-3 font-semibold">{t('adm_th_status')}</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-sage">
              {filtered.map(c => (
                <tr key={c.id} onClick={() => navigate(`/admin/clients/${c.id}`)} className="cursor-pointer hover:bg-cream/60">
                  <td className="p-3">
                    <div className="flex items-center gap-3">
                      <Avatar name={`${c.firstName} ${c.lastName}`} size={32} />
                      <div>
                        <div className="font-medium">{c.firstName} {c.lastName}</div>
                        <div className="text-xs text-ink/55">{c.email}</div>
                      </div>
                    </div>
                  </td>
                  <td className="p-3 text-ink/75">{c.plan}</td>
                  <td className="p-3 font-medium">{c.subscription.totalMenus - c.subscription.menusDelivered} / {c.subscription.totalMenus}</td>
                  <td className="p-3">
                    {c.validations.labTests.status === 'expired'
                      ? <Pill tone="coral">{t('val_expired')}</Pill>
                      : <Pill tone="green">{t('val_valid')}</Pill>}
                  </td>
                  <td className="p-3 text-ink/65 text-xs">{c.lastMenuDate || '—'}</td>
                  <td className="p-3"><Pill tone={c.subscription.status === 'active' ? 'green' : c.subscription.status === 'completed' ? 'purple' : 'beige'}>
                    {t(`status_${c.subscription.status}`)}
                  </Pill></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function AdminClientDetailPage({ params = {} }) {
  const t = useT();
  const { clients } = useApp();
  const { clientId } = params;
  const client = clients.find(c => c.id === clientId) || clients[0];
  const [tab, setTab] = React.useState('profile');

  const tabs = [
    { value: 'profile', label: t('adm_tab_profile') },
    { value: 'subscriptions', label: t('adm_tab_subs') },
    { value: 'labs', label: t('adm_tab_labs') },
    { value: 'psych', label: t('adm_tab_psych') },
    { value: 'allergies', label: t('adm_tab_allergies') },
    { value: 'menus', label: t('adm_tab_menus') },
    { value: 'frequency', label: t('adm_tab_frequency') },
    { value: 'validations', label: t('adm_tab_validations') },
  ];

  return (
    <div className="min-h-[calc(100vh-4rem)] bg-cream pb-16">
      <div className="max-w-7xl mx-auto px-4 md:px-8 py-8">
        <button onClick={() => navigate('/admin/clients')} className="text-olive text-sm mb-3 inline-flex items-center gap-1 hover:underline">
          <Icon name="arrow_left" size={13} /> {t('adm_back_clients')}
        </button>

        <div className="card p-5 mb-5 flex items-center gap-4 flex-wrap">
          <Avatar name={`${client.firstName} ${client.lastName}`} size={56} />
          <div className="flex-1 min-w-0">
            <h1 className="h1 text-2xl md:text-3xl">{client.firstName} {client.lastName}</h1>
            <div className="text-sm text-ink/55">{client.email} · {client.sex === 'female' ? 'F' : 'M'}, {client.age} ani · {client.plan}</div>
          </div>
          <div className="flex items-center gap-2">
            {client.validations.labTests.status === 'expired' && <Pill tone="coral">{t('val_lab_expired')}</Pill>}
            <Pill tone={client.subscription.status === 'active' ? 'green' : 'beige'}>{t(`status_${client.subscription.status}`)}</Pill>
          </div>
        </div>

        <Tabs value={tab} onChange={setTab} options={tabs} scroll />

        <div className="mt-5">
          {tab === 'profile' && <AdminTabProfile client={client} />}
          {tab === 'subscriptions' && <AdminTabSubs client={client} />}
          {tab === 'labs' && <AdminTabLabs client={client} />}
          {tab === 'psych' && <AdminTabPsych client={client} />}
          {tab === 'allergies' && <AdminTabAllergies client={client} />}
          {tab === 'menus' && <AdminTabMenus client={client} />}
          {tab === 'frequency' && <AdminTabFrequency client={client} />}
          {tab === 'validations' && <AdminTabValidations client={client} />}
        </div>
      </div>
    </div>
  );
}

function AdminTabProfile({ client }) {
  const t = useT();
  const rows = [
    [t('set_name'), `${client.firstName} ${client.lastName}`, '2024-08-12'],
    [t('set_email'), client.email, '2025-11-04'],
    [t('set_dob'), client.dob, '2024-08-12'],
    [t('set_height'), client.height + ' cm', '2024-08-12'],
    [t('onb_weight'), client.weight + ' kg', '2026-04-15'],
    [t('onb_activity'), t(`act_${client.activity}`), '2026-04-15'],
    [t('onb_goal'), t(`goal_${client.goal}`), '2026-04-15'],
    [t('onb_wakeup'), client.wakeUp || '07:00', '2026-04-15'],
  ];
  return (
    <div className="card overflow-hidden">
      <table className="w-full text-sm">
        <thead className="text-xs uppercase tracking-[0.1em] text-ink/55 bg-cream">
          <tr>
            <th className="text-left p-3 font-semibold">{t('adm_th_field')}</th>
            <th className="text-left p-3 font-semibold">{t('adm_th_value')}</th>
            <th className="text-left p-3 font-semibold">{t('adm_th_modified')}</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-sage">
          {rows.map((r, i) => (
            <tr key={i}>
              <td className="p-3 font-medium text-ink/65 text-xs uppercase tracking-[0.08em]">{r[0]}</td>
              <td className="p-3 font-medium">{r[1]}</td>
              <td className="p-3 text-ink/55 text-xs">{r[2]}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function AdminTabSubs({ client }) {
  const t = useT();
  const subs = client.subscriptionsHistory || [client.subscription];
  return (
    <div className="card overflow-hidden">
      <table className="w-full text-sm">
        <thead className="text-xs uppercase tracking-[0.1em] text-ink/55 bg-cream">
          <tr>
            <th className="text-left p-3 font-semibold">{t('adm_th_plan')}</th>
            <th className="text-left p-3 font-semibold">{t('billing_th_start')}</th>
            <th className="text-left p-3 font-semibold">{t('billing_th_end')}</th>
            <th className="text-left p-3 font-semibold">{t('adm_th_status')}</th>
            <th className="text-left p-3 font-semibold">{t('adm_th_payment')}</th>
            <th className="text-left p-3 font-semibold">{t('adm_th_delivered')}</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-sage">
          {subs.map((s, i) => (
            <tr key={i}>
              <td className="p-3 font-medium">{s.planName || client.plan}</td>
              <td className="p-3 text-ink/65">{s.startDate}</td>
              <td className="p-3 text-ink/65">{s.endDate}</td>
              <td className="p-3"><Pill tone={s.status === 'active' ? 'green' : s.status === 'completed' ? 'purple' : 'beige'}>{t(`status_${s.status}`)}</Pill></td>
              <td className="p-3"><Pill tone="green">{t('pay_paid')}</Pill></td>
              <td className="p-3 font-medium">{s.menusDelivered} / {s.totalMenus}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function AdminTabLabs({ client }) {
  const t = useT();
  const RC = window.Recharts || {};
  const cats = ['hepatic', 'renal', 'tumor', 'cardiac', 'metabolic', 'hormonal', 'vitamins'];
  const [activeCat, setActiveCat] = React.useState('vitamins');
  const labs = client.labResults || {};

  return (
    <div>
      <div className="card p-4 mb-4">
        <div className="flex items-center justify-between text-sm">
          <span className="text-ink/55">{t('adm_lab_date')}: <strong className="text-ink">{labs.date || '2026-04-15'}</strong></span>
          <Pill tone={client.validations.labTests.status === 'expired' ? 'coral' : 'green'}>
            {client.validations.labTests.status === 'expired' ? t('val_expired') : t('val_valid')}
          </Pill>
        </div>
      </div>
      <Tabs value={activeCat} onChange={setActiveCat} options={cats.map(c => ({ value: c, label: t(`lab_${c}`) }))} scroll />
      <div className="card overflow-hidden mt-4">
        <table className="w-full text-sm">
          <thead className="text-xs uppercase tracking-[0.1em] text-ink/55 bg-cream">
            <tr>
              <th className="text-left p-3 font-semibold">Marker</th>
              <th className="text-left p-3 font-semibold">{t('adm_th_value')}</th>
              <th className="text-left p-3 font-semibold">Interval</th>
              <th className="text-left p-3 font-semibold">{t('adm_th_status')}</th>
              <th className="text-left p-3 font-semibold">{t('adm_th_trend')}</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-sage">
            {window.LAB_TESTS[activeCat].map(test => {
              const v = labs.values?.[test.key];
              const status = v == null ? 'pending' : (v < test.refMin || v > test.refMax) ? 'outofrange' : 'normal';
              return (
                <tr key={test.key}>
                  <td className="p-3 font-medium">{test.name}</td>
                  <td className="p-3"><span className="font-bold text-base">{v ?? '—'}</span> <span className="text-xs text-ink/55">{test.unit}</span></td>
                  <td className="p-3 text-ink/55 text-xs">{test.refMin} – {test.refMax}</td>
                  <td className="p-3"><StatusPill status={status} /></td>
                  <td className="p-3"><MiniSpark value={v} min={test.refMin} max={test.refMax} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function MiniSpark({ value, min, max }) {
  if (value == null) return <span className="text-ink/30 text-xs">—</span>;
  const pct = Math.max(0, Math.min(1, (value - min) / (max - min || 1)));
  return (
    <svg width="80" height="22" viewBox="0 0 80 22">
      <line x1="2" y1="11" x2="78" y2="11" stroke="#EEF1E4" strokeWidth="2" />
      <line x1={2 + pct * 76 / 4} y1="11" x2={2 + pct * 76} y2="11" stroke="#417A3E" strokeWidth="2" />
      <circle cx={2 + pct * 76} cy="11" r="3.5" fill="#417A3E" />
    </svg>
  );
}

function AdminTabPsych({ client }) {
  const t = useT();
  const RC = window.Recharts || {};
  const totals = client.psychTotals || { anxiety: 10, stress: 7, sleep: 4, energy: 6, mood: 5 };
  const answers = client.psychAnswers || {};
  const notes = client.psychNotes;
  const date = client.psychDate || '2026-04-15';
  const data = Object.entries(totals).map(([k, v]) => ({ category: t(`cat_${k}`), key: k, value: v, max: 15 }));
  const hasChart = !!RC.BarChart;

  const PSYCH_Q = window.PSYCH_QUESTIONS || {};
  const scaleColor = (v) => v >= 3 ? 'bg-coral/15 text-coral' : v === 2 ? 'bg-warm-beige text-ink/80' : 'bg-green-primary/15 text-green-primary';

  return (
    <div className="space-y-5">
      <div className="card p-5">
        <div className="flex items-center justify-between mb-4 flex-wrap gap-2">
          <h3 className="serif text-lg font-semibold text-purple-primary">{t('adm_psych_summary')}</h3>
          <span className="text-xs text-ink/55">{t('adm_lab_date')}: {date}</span>
        </div>
        <div className="grid md:grid-cols-2 gap-6">
          <div className="h-72">
            {hasChart ? (
              <RC.ResponsiveContainer width="100%" height="100%">
                <RC.BarChart data={data} layout="vertical" margin={{ top: 0, right: 20, bottom: 0, left: 60 }}>
                  <RC.XAxis type="number" domain={[0, 15]} tick={{ fontSize: 11, fill: '#666' }} />
                  <RC.YAxis type="category" dataKey="category" tick={{ fontSize: 12, fill: '#212529' }} width={70} />
                  <RC.Bar dataKey="value" fill="#662D91" radius={[0, 8, 8, 0]} />
                </RC.BarChart>
              </RC.ResponsiveContainer>
            ) : (
              <div className="h-full flex flex-col justify-center gap-2">
                {data.map(d => (
                  <div key={d.key} className="flex items-center gap-2">
                    <span className="w-20 text-xs text-ink/65 text-right">{d.category}</span>
                    <div className="flex-1 h-6 rounded-full bg-cream overflow-hidden">
                      <div className="h-full bg-purple-primary rounded-full" style={{ width: `${(d.value / d.max) * 100}%` }} />
                    </div>
                    <span className="w-10 text-xs font-bold tabular-nums text-purple-primary">{d.value}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
          <div className="space-y-2">
            {data.map(d => {
              const tone = d.value >= 10 ? 'coral' : d.value >= 7 ? 'beige' : 'green';
              return (
                <div key={d.key} className="flex items-center justify-between p-3 rounded-2xl bg-cream">
                  <span className="text-sm font-medium">{d.category}</span>
                  <div className="flex items-center gap-2">
                    <Pill tone={tone}>{d.value >= 10 ? 'Ridicat' : d.value >= 7 ? 'Moderat' : 'Scăzut'}</Pill>
                    <span className="font-bold text-purple-primary tabular-nums">{d.value}<span className="text-xs text-ink/55 font-normal">/{d.max}</span></span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
        {notes && (
          <div className="mt-5 p-4 rounded-2xl bg-purple-primary/5 border-l-4 border-purple-primary">
            <div className="text-xs uppercase tracking-[0.12em] text-purple-primary font-semibold mb-1">Note clinice</div>
            <p className="text-sm text-ink/80 leading-relaxed">{notes}</p>
          </div>
        )}
      </div>

      {/* Per-question answers */}
      {Object.keys(answers).length > 0 && (
        <div className="card overflow-hidden">
          <div className="px-5 py-4 border-b border-sage bg-cream flex items-center justify-between">
            <h3 className="serif text-lg font-semibold text-purple-primary">Răspunsuri detaliate</h3>
            <span className="text-xs text-ink/55">15 întrebări · scală 0–4</span>
          </div>
          <div className="divide-y divide-sage">
            {Object.keys(totals).map(cat => {
              const qs = PSYCH_Q[cat] || [];
              const ans = answers[cat] || [];
              return (
                <div key={cat} className="p-5">
                  <div className="flex items-center gap-2 mb-3">
                    <span className="text-xs uppercase tracking-[0.12em] font-semibold text-purple-primary">{t(`cat_${cat}`)}</span>
                    <span className="text-xs text-ink/45 tabular-nums">subscor {totals[cat]}/15</span>
                  </div>
                  <div className="space-y-2">
                    {qs.map((q, i) => {
                      const v = ans[i] ?? 0;
                      return (
                        <div key={i} className="flex items-start gap-3">
                          <span className="text-ink/55 text-xs mt-1 w-5 tabular-nums">{i + 1}.</span>
                          <span className="flex-1 text-sm text-ink/80">{q}</span>
                          <span className={cls("text-xs font-semibold px-2.5 py-1 rounded-full whitespace-nowrap", scaleColor(v))}>{t(`psych_scale_${v}`)}</span>
                        </div>
                      );
                    })}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

function AdminTabAllergies({ client }) {
  const t = useT();
  return (
    <div className="grid md:grid-cols-3 gap-5">
      <div className="card p-5">
        <h3 className="serif text-lg font-semibold text-purple-primary mb-3">{t('val_allergies')}</h3>
        {client.allergies?.length ? (
          <div className="flex flex-wrap gap-2">
            {client.allergies.map(a => (
              <span key={a} className="px-3 py-1.5 rounded-full bg-coral/15 text-coral text-sm font-medium">
                <Icon name="alert" size={11} className="inline mr-1" /> {a}
              </span>
            ))}
          </div>
        ) : <div className="text-xs text-ink/55">—</div>}
      </div>
      <div className="card p-5">
        <h3 className="serif text-lg font-semibold text-purple-primary mb-3">{t('val_prefs')}</h3>
        <div className="space-y-2 text-sm">
          {Object.entries(client.preferences || {}).map(([k, v]) => (
            <div key={k} className="flex items-center justify-between">
              <span className="text-ink/75">{t(`pref_${k}`)}</span>
              <span className={cls("text-xs font-semibold px-2 py-0.5 rounded-full", v ? 'bg-green-primary/15 text-green-primary' : 'bg-sage text-ink/55')}>{v ? 'Da' : 'Nu'}</span>
            </div>
          ))}
        </div>
      </div>
      <div className="card p-5">
        <h3 className="serif text-lg font-semibold text-purple-primary mb-3">{t('adm_disliked')}</h3>
        <div className="text-xs text-ink/55 mb-1">{t('adm_disliked_foods')}</div>
        <div className="flex flex-wrap gap-1.5 mb-3">
          {(client.dislikedFoods || []).map(f => <span key={f} className="px-2.5 py-1 rounded-full bg-sage text-xs">{f}</span>)}
        </div>
        <div className="text-xs text-ink/55 mb-1">{t('adm_disliked_drinks')}</div>
        <div className="flex flex-wrap gap-1.5">
          {(client.dislikedDrinks || []).map(f => <span key={f} className="px-2.5 py-1 rounded-full bg-sage text-xs">{f}</span>)}
        </div>
      </div>
    </div>
  );
}

function AdminTabMenus({ client }) {
  const t = useT();
  const [view, setView] = React.useState('list');
  const [openMenu, setOpenMenu] = React.useState(null);
  const menus = [
    { id: 1, week: 1, start: '2026-04-20', status: 'delivered' },
    { id: 2, week: 2, start: '2026-05-04', status: 'delivered' },
    { id: 3, week: 3, start: '2026-05-18', status: 'pending' },
  ];
  return (
    <div>
      <div className="card overflow-hidden">
        <table className="w-full text-sm">
          <thead className="text-xs uppercase tracking-[0.1em] text-ink/55 bg-cream">
            <tr>
              <th className="text-left p-3 font-semibold">{t('dash_th_week')}</th>
              <th className="text-left p-3 font-semibold">{t('billing_th_start')}</th>
              <th className="text-left p-3 font-semibold">{t('adm_th_status')}</th>
              <th className="text-right p-3 font-semibold">{t('adm_th_actions')}</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-sage">
            {menus.map(m => (
              <tr key={m.id}>
                <td className="p-3 font-medium">{t('menu_week', m.week)}</td>
                <td className="p-3 text-ink/65">{m.start}</td>
                <td className="p-3"><Pill tone={m.status === 'delivered' ? 'green' : 'beige'}>{m.status === 'delivered' ? t('status_delivered') : t('status_generating')}</Pill></td>
                <td className="p-3 text-right">
                  <Button size="sm" variant="ghost" onClick={() => setOpenMenu(m)}><Icon name="eye" size={13} /> {t('adm_view_menu')}</Button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <Modal open={!!openMenu} onClose={() => setOpenMenu(null)} title={openMenu && t('menu_week', openMenu.week)} size="lg">
        <div className="flex gap-2 mb-4">
          <button onClick={() => setView('list')} className={cls("px-3 py-1.5 rounded-full text-xs font-semibold", view === 'list' ? 'bg-green-primary text-white' : 'bg-sage')}>{t('adm_view_client')}</button>
          <button onClick={() => setView('raw')} className={cls("px-3 py-1.5 rounded-full text-xs font-semibold", view === 'raw' ? 'bg-purple-primary text-white' : 'bg-sage')}>{t('adm_view_raw')}</button>
        </div>
        {view === 'list' ? (
          <div className="space-y-3 max-h-[60vh] overflow-y-auto">
            {window.MENU_7DAYS[0].meals.map((m, i) => (
              <div key={i} className="border border-sage rounded-2xl p-4">
                <div className="flex items-center justify-between mb-2">
                  <strong>{m.time} · {t(`meal_${m.type}`)}</strong>
                  <span className="text-sm text-green-primary font-semibold">{m.kcal} kcal</span>
                </div>
                <ul className="text-sm space-y-1">
                  {m.items.map((it, j) => <li key={j} className="flex justify-between"><span>{it.name}</span><RuleSourcePill source={it.ruleSource} /></li>)}
                </ul>
              </div>
            ))}
          </div>
        ) : (
          <div className="overflow-x-auto max-h-[60vh]">
            <table className="w-full text-xs">
              <thead className="bg-cream text-ink/55 uppercase tracking-[0.08em]">
                <tr><th className="text-left p-2">Day</th><th className="text-left p-2">Meal</th><th className="text-left p-2">Food</th><th className="text-left p-2">Serving</th><th className="text-left p-2">kcal</th><th className="text-left p-2">ruleSource</th></tr>
              </thead>
              <tbody className="divide-y divide-sage font-mono">
                {window.MENU_7DAYS.flatMap((d, di) => d.meals.flatMap(meal => meal.items.map(it => ({ day: di + 1, meal: meal.type, ...it })))).map((row, i) => (
                  <tr key={i}>
                    <td className="p-2">{row.day}</td>
                    <td className="p-2">{row.meal}</td>
                    <td className="p-2">{row.name}</td>
                    <td className="p-2">{row.serving}</td>
                    <td className="p-2">{row.kcal || '—'}</td>
                    <td className="p-2"><Pill tone={row.ruleSource === 'lab' ? 'purple' : row.ruleSource === 'psych' ? 'beige' : row.ruleSource === 'preference' ? 'green' : 'neutral'}>{row.ruleSource}</Pill></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Modal>
    </div>
  );
}

function AdminTabFrequency({ client }) {
  const t = useT();
  const items = [
    { name: 'Iaurt grecesc', last: '2026-05-04', last30: 8, total: 24 },
    { name: 'Ouă fierte', last: '2026-05-05', last30: 7, total: 20 },
    { name: 'Quinoa', last: '2026-05-04', last30: 6, total: 16 },
    { name: 'Hummus', last: '2026-05-05', last30: 4, total: 12 },
    { name: 'Banane', last: '2026-05-05', last30: 5, total: 15 },
    { name: 'Salată verde', last: '2026-05-04', last30: 6, total: 18 },
  ];
  const drinks = [
    { name: 'Ceai verde', last: '2026-05-05', last30: 14, total: 42 },
    { name: 'Apă plată', last: '2026-05-05', last30: 30, total: 88 },
    { name: 'Ceai de mușețel', last: '2026-05-04', last30: 7, total: 21 },
  ];
  return (
    <div className="space-y-5">
      {[['Alimente', items], ['Băuturi', drinks]].map(([title, rows]) => (
        <div key={title} className="card overflow-hidden">
          <div className="px-4 py-3 border-b border-sage bg-cream">
            <h3 className="serif text-base font-semibold text-purple-primary">{title}</h3>
          </div>
          <table className="w-full text-sm">
            <thead className="text-xs uppercase tracking-[0.1em] text-ink/55 bg-white border-b border-sage">
              <tr>
                <th className="text-left p-3 font-semibold">{t('adm_th_item')}</th>
                <th className="text-left p-3 font-semibold">{t('adm_th_last_used')}</th>
                <th className="text-right p-3 font-semibold">{t('adm_th_30days')}</th>
                <th className="text-right p-3 font-semibold">{t('adm_th_total')}</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-sage">
              {rows.map((r, i) => (
                <tr key={i}>
                  <td className="p-3 font-medium">{r.name}</td>
                  <td className="p-3 text-ink/65 text-xs">{r.last}</td>
                  <td className="p-3 text-right font-semibold">{r.last30}</td>
                  <td className="p-3 text-right text-ink/55">{r.total}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ))}
    </div>
  );
}

function AdminTabValidations({ client }) {
  const t = useT();
  const items = [
    ['labTests', t('val_lab')],
    ['psychAssessment', t('val_psych')],
    ['allergies', t('val_allergies')],
    ['preferences', t('val_prefs')],
  ];
  return (
    <div className="card overflow-hidden">
      <table className="w-full text-sm">
        <thead className="text-xs uppercase tracking-[0.1em] text-ink/55 bg-cream">
          <tr>
            <th className="text-left p-3 font-semibold">{t('adm_th_validation')}</th>
            <th className="text-left p-3 font-semibold">{t('adm_th_last_update')}</th>
            <th className="text-left p-3 font-semibold">{t('adm_th_next_required')}</th>
            <th className="text-left p-3 font-semibold">{t('adm_th_status')}</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-sage">
          {items.map(([k, lbl]) => {
            const v = client.validations[k];
            return (
              <tr key={k}>
                <td className="p-3 font-medium">{lbl}</td>
                <td className="p-3 text-ink/65 text-xs">{v.lastUpdatedDate}</td>
                <td className="p-3 text-ink/65 text-xs">{v.nextRequiredUpdateDate}</td>
                <td className="p-3">
                  {v.status === 'expired' ? <Pill tone="coral">{t('val_expired')}</Pill>
                    : v.status === 'pending_update' ? <Pill tone="beige">{t('val_pending')}</Pill>
                    : <Pill tone="green">{t('val_valid')}</Pill>}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

function AdminMenusPage() {
  const t = useT();
  const { clients } = useApp();
  const [tab, setTab] = React.useState('queue');

  // Synthetic operational queue — what actually matters with thousands of clients
  const today = '2026-05-07';
  const queue = [
    { id: 'q1', client: 'Mihai Ionescu', clientId: 'mihai', plan: 'Premium', dueDate: '2026-05-08', status: 'overdue',
      reason: 'Generare programată ieri — încă nu este trimisă', priority: 'high' },
    { id: 'q2', client: 'Ana Popescu',   clientId: 'ana',   plan: 'Standard', dueDate: '2026-05-11', status: 'ready',
      reason: 'Toate validările OK · gata de generare', priority: 'normal' },
    { id: 'q3', client: 'Elena Dumitrescu', clientId: 'elena', plan: 'Starter', dueDate: '2026-05-09', status: 'blocked',
      reason: 'Analize expirate — necesită reactualizare înainte', priority: 'high' },
    { id: 'q4', client: 'Mihai Ionescu', clientId: 'mihai', plan: 'Premium', dueDate: '2026-05-15', status: 'scheduled',
      reason: 'Programat pentru săptămâna viitoare', priority: 'normal' },
    { id: 'q5', client: 'Ana Popescu',   clientId: 'ana',   plan: 'Standard', dueDate: '2026-05-13', status: 'review',
      reason: '2 alimente repetate consecutiv 4× — verifică varietatea', priority: 'normal' },
    { id: 'q6', client: 'Elena Dumitrescu', clientId: 'elena', plan: 'Starter', dueDate: '2026-05-22', status: 'scheduled',
      reason: 'Programat', priority: 'normal' },
  ];
  const counts = {
    overdue: queue.filter(q => q.status === 'overdue').length,
    blocked: queue.filter(q => q.status === 'blocked').length,
    review:  queue.filter(q => q.status === 'review').length,
    ready:   queue.filter(q => q.status === 'ready').length,
    scheduled: queue.filter(q => q.status === 'scheduled').length,
  };

  const tabs = [
    { value: 'queue', label: `Cozi de lucru (${queue.length})` },
    { value: 'calendar', label: 'Calendar săptămânal' },
  ];

  const statusMeta = {
    overdue:   { tone: 'coral',  label: 'Întârziat',         icon: 'alert' },
    blocked:   { tone: 'coral',  label: 'Blocat',            icon: 'lock' },
    review:    { tone: 'beige',  label: 'De verificat',      icon: 'eye' },
    ready:     { tone: 'green',  label: 'Gata de generat',   icon: 'check' },
    scheduled: { tone: 'purple', label: 'Programat',         icon: 'calendar' },
  };

  return (
    <div className="min-h-[calc(100vh-4rem)] bg-cream pb-16">
      <div className="max-w-7xl mx-auto px-4 md:px-8 py-8">
        <div className="flex items-end justify-between flex-wrap gap-3 mb-1">
          <h1 className="h1 text-3xl">Operațiuni meniuri</h1>
          <span className="text-xs text-ink/55">Ziua de azi: {today}</span>
        </div>
        <p className="text-ink/55 mb-6">Ce trebuie făcut astăzi pentru a livra meniurile la timp — focus pe acțiunile blocate, întârziate și de verificat.</p>

        {/* Operational KPIs */}
        <div className="grid grid-cols-2 md:grid-cols-5 gap-3 mb-6">
          {[
            { k: 'overdue',  label: 'Întârziate',     tone: 'bg-coral text-white' },
            { k: 'blocked',  label: 'Blocate',        tone: 'bg-coral/15 text-coral' },
            { k: 'review',   label: 'De verificat',   tone: 'bg-warm-beige text-ink' },
            { k: 'ready',    label: 'Gata de generat',tone: 'bg-green-primary text-white' },
            { k: 'scheduled',label: 'Programate',     tone: 'bg-purple-primary/15 text-purple-primary' },
          ].map(card => (
            <div key={card.k} className={cls("rounded-2xl p-4", card.tone)}>
              <div className="text-3xl font-bold serif tabular-nums leading-none">{counts[card.k]}</div>
              <div className="text-xs uppercase tracking-[0.1em] mt-2 opacity-90">{card.label}</div>
            </div>
          ))}
        </div>

        <Tabs value={tab} onChange={setTab} options={tabs} />

        {tab === 'queue' && (
          <div className="card overflow-hidden mt-5">
            <table className="w-full text-sm">
              <thead className="text-xs uppercase tracking-[0.1em] text-ink/55 bg-cream">
                <tr>
                  <th className="text-left p-3 font-semibold">Status</th>
                  <th className="text-left p-3 font-semibold">Client</th>
                  <th className="text-left p-3 font-semibold">Plan</th>
                  <th className="text-left p-3 font-semibold">Termen</th>
                  <th className="text-left p-3 font-semibold">Detalii</th>
                  <th className="text-right p-3 font-semibold">Acțiuni</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-sage">
                {[...queue].sort((a, b) => {
                  const order = { overdue: 0, blocked: 1, review: 2, ready: 3, scheduled: 4 };
                  return order[a.status] - order[b.status] || a.dueDate.localeCompare(b.dueDate);
                }).map(q => {
                  const m = statusMeta[q.status];
                  const overdue = q.status === 'overdue';
                  return (
                    <tr key={q.id} className={cls("hover:bg-cream/60", overdue && 'bg-coral/5')}>
                      <td className="p-3"><Pill tone={m.tone}><Icon name={m.icon} size={11} /> {m.label}</Pill></td>
                      <td className="p-3 font-medium">
                        <button onClick={() => navigate(`/admin/clients/${q.clientId}`)} className="hover:underline text-left">{q.client}</button>
                      </td>
                      <td className="p-3 text-ink/65">{q.plan}</td>
                      <td className={cls("p-3 tabular-nums text-xs", overdue ? 'text-coral font-semibold' : 'text-ink/65')}>{q.dueDate}</td>
                      <td className="p-3 text-ink/75 text-xs max-w-md">{q.reason}</td>
                      <td className="p-3 text-right whitespace-nowrap">
                        {q.status === 'ready' && <Button size="sm" variant="primary"><Icon name="spark" size={12} /> Generează</Button>}
                        {q.status === 'review' && <Button size="sm" variant="outline"><Icon name="eye" size={12} /> Verifică</Button>}
                        {q.status === 'overdue' && <Button size="sm" variant="primary"><Icon name="play" size={12} /> Trimite acum</Button>}
                        {q.status === 'blocked' && <Button size="sm" variant="outline" onClick={() => navigate(`/admin/clients/${q.clientId}`)}><Icon name="arrow_right" size={12} /> Deblochează</Button>}
                        {q.status === 'scheduled' && <Button size="sm" variant="ghost"><Icon name="more" size={12} /></Button>}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}

        {tab === 'calendar' && (
          <div className="card p-5 mt-5">
            <div className="flex items-center justify-between mb-4">
              <h3 className="serif text-lg font-semibold text-purple-primary">Săptămâna 4–10 mai</h3>
              <span className="text-xs text-ink/55">{queue.length} sarcini</span>
            </div>
            <div className="grid grid-cols-7 gap-2">
              {['Lun', 'Mar', 'Mie', 'Joi', 'Vin', 'Sâm', 'Dum'].map((d, i) => {
                const date = `2026-05-${String(4 + i).padStart(2, '0')}`;
                const dayQ = queue.filter(q => q.dueDate === date);
                const isToday = date === today;
                return (
                  <div key={d} className={cls("rounded-xl border p-3 min-h-[140px]", isToday ? 'border-green-primary bg-green-primary/5' : 'border-sage bg-white')}>
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-xs uppercase tracking-[0.1em] text-ink/55 font-semibold">{d}</span>
                      <span className={cls("text-sm font-bold tabular-nums", isToday ? 'text-green-primary' : 'text-ink/65')}>{4 + i}</span>
                    </div>
                    <div className="space-y-1.5">
                      {dayQ.map(q => {
                        const m = statusMeta[q.status];
                        return (
                          <div key={q.id} className={cls("text-[10px] leading-tight px-1.5 py-1.5 rounded font-medium",
                            q.status === 'overdue' || q.status === 'blocked' ? 'bg-coral/15 text-coral'
                              : q.status === 'review' ? 'bg-warm-beige text-ink/80'
                              : q.status === 'ready' ? 'bg-green-primary/15 text-green-primary'
                              : 'bg-purple-primary/15 text-purple-primary')}>
                            <div className="font-semibold truncate">{q.client.split(' ')[0]}</div>
                            <div className="opacity-75 truncate">{m.label}</div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function AdminSubscriptionsPage() {
  const t = useT();
  const { clients } = useApp();
  const [filter, setFilter] = React.useState('all');
  const rows = clients.flatMap(c => (c.subscriptionsHistory || [c.subscription]).map(s => ({
    client: `${c.firstName} ${c.lastName}`,
    plan: s.planName || c.plan,
    start: s.startDate, end: s.endDate, status: s.status,
    amount: s.amount || (c.plan.includes('Premium') ? 2000 : c.plan.includes('Starter') ? 600 : 1100),
    payment: s.paymentStatus || 'paid',
  })));
  const filtered = rows.filter(r => filter === 'all' ? true : r.payment === filter);

  return (
    <div className="min-h-[calc(100vh-4rem)] bg-cream pb-16">
      <div className="max-w-7xl mx-auto px-4 md:px-8 py-8">
        <h1 className="h1 text-3xl mb-1">{t('adm_subs')}</h1>
        <p className="text-ink/55 mb-5">{t('adm_subs_count', rows.length)}</p>

        <div className="flex gap-2 mb-4">
          {[['all', t('filter_all')], ['paid', t('pay_paid')], ['pending', t('pay_pending')], ['refunded', t('pay_refunded')]].map(([v, lbl]) => (
            <button key={v} onClick={() => setFilter(v)}
              className={cls("px-4 py-2 rounded-full text-xs font-medium border",
                filter === v ? 'bg-purple-primary text-white border-purple-primary' : 'bg-white border-sage text-ink/70')}>
              {lbl}
            </button>
          ))}
        </div>

        <div className="card overflow-hidden">
          <table className="w-full text-sm">
            <thead className="text-xs uppercase tracking-[0.1em] text-ink/55 bg-cream">
              <tr>
                <th className="text-left p-3 font-semibold">{t('adm_th_client')}</th>
                <th className="text-left p-3 font-semibold">{t('adm_th_plan')}</th>
                <th className="text-left p-3 font-semibold">{t('billing_th_start')}</th>
                <th className="text-left p-3 font-semibold">{t('billing_th_end')}</th>
                <th className="text-right p-3 font-semibold">{t('billing_th_amount')}</th>
                <th className="text-left p-3 font-semibold">{t('adm_th_status')}</th>
                <th className="text-left p-3 font-semibold">{t('adm_th_payment')}</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-sage">
              {filtered.map((r, i) => (
                <tr key={i}>
                  <td className="p-3 font-medium">{r.client}</td>
                  <td className="p-3 text-ink/75">{r.plan}</td>
                  <td className="p-3 text-ink/65 text-xs">{r.start}</td>
                  <td className="p-3 text-ink/65 text-xs">{r.end}</td>
                  <td className="p-3 text-right font-semibold">{r.amount} RON</td>
                  <td className="p-3"><Pill tone={r.status === 'active' ? 'green' : r.status === 'completed' ? 'purple' : 'beige'}>{t(`status_${r.status}`)}</Pill></td>
                  <td className="p-3"><Pill tone={r.payment === 'paid' ? 'green' : r.payment === 'pending' ? 'beige' : 'coral'}>{t(`pay_${r.payment}`)}</Pill></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  AdminDashboardPage, AdminClientsPage, AdminClientDetailPage,
  AdminMenusPage, AdminSubscriptionsPage,
});
// App entry — adapts data shapes for pages, mounts router

// ---- Adapter: normalize data + extend useApp ----
(function setupAdapters() {
  // Map ANA_WEEK (mealType, items[].food, .amount) -> MENU_7DAYS (type, items[].name, .serving)
  const RULE_REASONS = {
    lab: 'Această recomandare se bazează pe valoarea ta de Vitamina D = 15 ng/mL (deficit). Salmon, ouă și ciuperci sunt surse bune de vit. D.',
    psych: 'Recomandare aleasă pentru efectul calmant — nivelul tău de anxietate este ridicat (10/15).',
    preference: 'Această alegere respectă preferințele tale (vegetarian, fără cafea).',
    default: 'Selectat pentru a echilibra macronutrienții și caloriile zilei.',
  };
  window.MENU_7DAYS = (window.ANA_WEEK || []).map(day => ({
    meals: (day || []).map(m => ({
      type: m.mealType,
      time: m.time,
      kcal: m.kcal,
      items: (m.items || []).map(it => ({
        name: it.food,
        serving: it.amount,
        kcal: it.kcal,
        ruleSource: it.ruleSource,
        reason: RULE_REASONS[it.ruleSource] || RULE_REASONS.default,
      })),
    })),
  }));

  // Build CLIENTS array (Ana + 3 dummy) with shape pages expect
  const ana = window.ANA || {};
  const today = new Date('2026-05-07');
  const days = (a, b) => Math.round((new Date(b) - new Date(a)) / 86400000);
  const enrichValidations = (v) => {
    const out = {};
    Object.keys(v || {}).forEach(k => {
      out[k] = {
        ...v[k],
        daysToExpire: days(today, v[k].nextRequiredUpdateDate),
      };
    });
    return out;
  };

  const computeAge = (dob) => Math.floor((today - new Date(dob)) / (365.25 * 86400000));
  const anaClient = {
    id: 'ana', firstName: 'Ana', lastName: 'Popescu', email: 'ana.popescu@example.com',
    sex: 'female', age: computeAge('1991-03-12'), dob: '1991-03-12',
    height: 165, weight: 75, activity: 'moderate', goal: 'lose_weight', wakeUp: '07:00',
    plan: 'Pachet Standard',
    subscription: { planName: 'Pachet Standard', status: 'active', startDate: '2026-04-20', endDate: '2026-07-13', menusDelivered: 2, totalMenus: 6, amount: 1100, paymentStatus: 'paid' },
    subscriptionsHistory: [
      { planName: 'Pachet Standard', status: 'active', startDate: '2026-04-20', endDate: '2026-07-13', menusDelivered: 2, totalMenus: 6, amount: 1100, paymentStatus: 'paid' },
    ],
    validations: enrichValidations(ana.validations),
    allergies: ana.allergies, preferences: ana.preferences,
    dislikedFoods: ana.dislikedFoods, dislikedDrinks: ana.dislikedDrinks,
    labResults: { date: ana.labResults.date, values: ana.labValues || {} },
    psychTotals: ana.psych.totals,
    psychAnswers: ana.psych.answers,
    psychNotes: ana.psych.notes,
    psychDate: ana.psych.date,
    lastMenuDate: '2026-05-04',
  };

  const mihai = {
    id: 'mihai', firstName: 'Mihai', lastName: 'Ionescu', email: 'mihai.i@example.com',
    sex: 'male', age: 42, dob: '1984-02-04', height: 182, weight: 88,
    activity: 'active', goal: 'maintain', plan: 'Pachet Premium',
    subscription: { planName: 'Pachet Premium', status: 'active', startDate: '2026-02-10', endDate: '2026-07-28', menusDelivered: 8, totalMenus: 12, amount: 2000, paymentStatus: 'paid' },
    subscriptionsHistory: [
      { planName: 'Pachet Premium', status: 'active', startDate: '2026-02-10', endDate: '2026-07-28', menusDelivered: 8, totalMenus: 12, amount: 2000, paymentStatus: 'paid' },
    ],
    validations: {
      labTests: { lastUpdatedDate: '2026-01-12', nextRequiredUpdateDate: '2026-07-12', status: 'valid', daysToExpire: 66 },
      psychAssessment: { lastUpdatedDate: '2026-01-12', nextRequiredUpdateDate: '2026-07-12', status: 'valid', daysToExpire: 66 },
      allergies: { lastUpdatedDate: '2025-08-12', nextRequiredUpdateDate: '2026-08-12', status: 'valid', daysToExpire: 97 },
      preferences: { lastUpdatedDate: '2025-08-12', nextRequiredUpdateDate: '2026-02-12', status: 'pending_update', daysToExpire: -84 },
    },
    allergies: ['Lactate'], preferences: { vegan: false, vegetarian: false, lactoseIntolerant: true, glutenIntolerant: false, dislikesSpicy: false },
    dislikedFoods: ['Vinete'], dislikedDrinks: [],
    labResults: { date: '2026-01-12', values: { vitamin_d: 32, hemoglobin: 14.8, tsh: 1.6, glucose: 98, cholesterol: 210 } },
    psychTotals: { anxiety: 5, stress: 6, sleep: 7, energy: 8, mood: 7 },
    lastMenuDate: '2026-04-29',
  };

  const elena = {
    id: 'elena', firstName: 'Elena', lastName: 'Dumitrescu', email: 'elena.d@example.com',
    sex: 'female', age: 28, dob: '1998-06-22', height: 170, weight: 62,
    activity: 'light', goal: 'gain_muscle', plan: 'Pachet Starter',
    subscription: { planName: 'Pachet Starter', status: 'active', startDate: '2026-04-01', endDate: '2026-05-13', menusDelivered: 1, totalMenus: 3, amount: 600, paymentStatus: 'paid' },
    subscriptionsHistory: [
      { planName: 'Pachet Starter', status: 'active', startDate: '2026-04-01', endDate: '2026-05-13', menusDelivered: 1, totalMenus: 3, amount: 600, paymentStatus: 'paid' },
    ],
    validations: {
      labTests: { lastUpdatedDate: '2025-08-15', nextRequiredUpdateDate: '2026-02-15', status: 'expired', daysToExpire: -81 },
      psychAssessment: { lastUpdatedDate: '2026-03-01', nextRequiredUpdateDate: '2026-09-01', status: 'valid', daysToExpire: 117 },
      allergies: { lastUpdatedDate: '2025-08-15', nextRequiredUpdateDate: '2026-08-15', status: 'valid', daysToExpire: 100 },
      preferences: { lastUpdatedDate: '2025-08-15', nextRequiredUpdateDate: '2026-02-15', status: 'pending_update', daysToExpire: -81 },
    },
    allergies: ['Gluten'], preferences: { vegan: false, vegetarian: true, lactoseIntolerant: false, glutenIntolerant: true, dislikesSpicy: false },
    dislikedFoods: [], dislikedDrinks: ['Cafea espresso'],
    labResults: { date: '2025-08-15', values: { vitamin_d: 22, hemoglobin: 12.4, tsh: 3.0, glucose: 88 } },
    psychTotals: { anxiety: 8, stress: 9, sleep: 5, energy: 4, mood: 6 },
    lastMenuDate: '2026-04-12',
  };

  const radu = {
    id: 'radu', firstName: 'Radu', lastName: 'Stan', email: 'radu.s@example.com',
    sex: 'male', age: 51, dob: '1975-03-08', height: 178, weight: 90,
    activity: 'sedentary', goal: 'improve_health', plan: 'Pachet Standard',
    subscription: { planName: 'Pachet Standard', status: 'completed', startDate: '2025-12-01', endDate: '2026-02-23', menusDelivered: 6, totalMenus: 6, amount: 1100, paymentStatus: 'paid' },
    subscriptionsHistory: [
      { planName: 'Pachet Standard', status: 'completed', startDate: '2025-12-01', endDate: '2026-02-23', menusDelivered: 6, totalMenus: 6, amount: 1100, paymentStatus: 'paid' },
    ],
    validations: {
      labTests: { lastUpdatedDate: '2025-11-20', nextRequiredUpdateDate: '2026-05-20', status: 'pending_update', daysToExpire: 13 },
      psychAssessment: { lastUpdatedDate: '2025-11-20', nextRequiredUpdateDate: '2026-05-20', status: 'pending_update', daysToExpire: 13 },
      allergies: { lastUpdatedDate: '2025-11-20', nextRequiredUpdateDate: '2026-11-20', status: 'valid', daysToExpire: 197 },
      preferences: { lastUpdatedDate: '2025-11-20', nextRequiredUpdateDate: '2026-05-20', status: 'pending_update', daysToExpire: 13 },
    },
    allergies: [], preferences: { vegan: false, vegetarian: false, lactoseIntolerant: false, glutenIntolerant: false, dislikesSpicy: true },
    dislikedFoods: ['Spanac'], dislikedDrinks: [],
    labResults: { date: '2025-11-20', values: { vitamin_d: 28, hemoglobin: 15.1, tsh: 2.4, glucose: 105, cholesterol: 230 } },
    psychTotals: { anxiety: 4, stress: 5, sleep: 6, energy: 7, mood: 7 },
    lastMenuDate: '2026-02-23',
  };

  window.CLIENTS = [anaClient, mihai, elena, radu];

  // Wrap useApp to expose subscription/validations/clients/setSubscription
  const baseUseApp = window.useApp;
  window.useApp = function () {
    const ctx = baseUseApp();
    const { ana: rawAna, subOverride, setSubOverride, demoMode } = ctx;
    const subscription = React.useMemo(() => {
      const base = anaClient.subscription;
      if (demoMode === 'first_menu') return { ...base, menusDelivered: 0 };
      if (subOverride) return { ...base, ...subOverride };
      return base;
    }, [demoMode, subOverride]);
    const setSubscription = React.useCallback((next) => {
      setSubOverride(next);
    }, [setSubOverride]);
    const validations = React.useMemo(() => {
      const v = JSON.parse(JSON.stringify(anaClient.validations));
      if (demoMode === 'expired_labs') {
        v.labTests.status = 'expired';
        v.labTests.daysToExpire = -30;
      }
      return v;
    }, [demoMode]);
    return {
      ...ctx,
      ana: anaClient,
      subscription,
      setSubscription,
      validations,
      clients: window.CLIENTS,
    };
  };
})();

// ---- App ----
function App() {
  return (
    <LocaleProvider>
      <RouterProvider>
        <AppProvider>
          <ToastProvider>
            <Layout />
          </ToastProvider>
        </AppProvider>
      </RouterProvider>
    </LocaleProvider>
  );
}

function Layout() {
  const { path } = useRouter();
  const { role, demoMode } = useApp();

  // Redirect guards
  React.useEffect(() => {
    const clientPaths = ['/account', '/onboarding'];
    const adminPaths = ['/admin'];
    if (role === 'visitor' && (clientPaths.some(p => path.startsWith(p)) || (adminPaths.some(p => path.startsWith(p)) && path !== '/admin/login'))) {
      // Not strictly redirecting — let user explore in demo, but the demo switcher will help
    }
  }, [path, role]);

  // Hide nav on auth pages
  const hideNav = ['/login', '/signup', '/forgot-password', '/reset-password', '/admin/login'].some(p => path.startsWith(p));

  return (
    <div className="min-h-screen flex flex-col">
      {!hideNav && <Nav />}
      <main className="flex-1">
        <Routes />
      </main>
      <DemoSwitcher />
    </div>
  );
}

function Routes() {
  const { path } = useRouter();

  // Static routes
  const staticMap = {
    '/': LandingPage,
    '/plans': PlansPage,
    '/checkout/success': CheckoutSuccessPage,
    '/signup': SignupPage,
    '/login': LoginPage,
    '/forgot-password': ForgotPasswordPage,
    '/reset-password': ResetPasswordPage,
    '/terms': TermsPage,
    '/onboarding': OnboardingPage,
    '/onboarding/complete': OnboardingCompletePage,
    '/account': AccountDashboardPage,
    '/account/renew': RenewalPage,
    '/account/settings': SettingsPage,
    '/account/settings/billing': BillingPage,
    '/account/settings/subscription': SubscriptionMgmtPage,
    '/profiles': ProfilesPage,
    '/admin/login': AdminLoginPage,
    '/admin': AdminDashboardPage,
    '/admin/clients': AdminClientsPage,
    '/admin/menus': AdminMenusPage,
    '/admin/subscriptions': AdminSubscriptionsPage,
  };
  if (staticMap[path]) {
    const Page = staticMap[path];
    return <div className="fade-up"><Page /></div>;
  }

  // Dynamic routes
  let m;
  if ((m = matchRoute('/account/menu/:menuId', path))) {
    return <div className="fade-up"><MenuViewerPage params={m} /></div>;
  }
  if ((m = matchRoute('/admin/clients/:clientId', path))) {
    return <div className="fade-up"><AdminClientDetailPage params={m} /></div>;
  }

  return (
    <div className="min-h-[calc(100vh-4rem)] flex items-center justify-center">
      <div className="text-center">
        <div className="serif text-6xl text-purple-primary font-semibold mb-2">404</div>
        <p className="text-ink/55 mb-4">Pagina nu există: {path}</p>
        <Button variant="primary" onClick={() => navigate('/')}>Acasă</Button>
      </div>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
