// ═══════════════════════════════════════════════════════════════
//  Support & Communication — technical support form + email
//  notification preferences. Each user can configure what events
//  trigger a notification email.
//
//  No real SMTP wired yet — emails are queued to state.emailOutbox
//  (visible to admins as "סטטוס תקשורת"). Once backend lands, a
//  cron job picks up queued=true and sends via SendGrid / SES / etc.
// ═══════════════════════════════════════════════════════════════

const { useState: uSS, useEffect: uES, useRef: uRS } = React;

// Human-readable labels for each app route — shown in support tickets
// so the admin immediately knows which page the user was on.
window.PAGE_LABELS = {
  dashboard:                'לוח בקרה',
  programs:                 'תכנית העבודה',
  'new-activity':           'פעילות חדשה',
  'edit-activity':          'עריכת פעילות',
  'activity-detail':        'דף פעילות',
  approvals:                'אישורים ממתינים',
  authorities:              'רשויות מקומיות',
  'authority-detail':       'דף רשות',
  payments:                 'דרישות תשלום',
  'payments-old':           'דרישות תשלום (ישן)',
  upload:                   'העלאת קובץ',
  basket:                   'סל פעילויות',
  coordinators:             'רכזים',
  settings:                 'הגדרות מערכת',
  audit:                    'בקרת אשד',
  calendar:                 'יומן מפגשים',
  'route-planner':          'מסלול ביקורים',
  community:                'שיתוף קהילה',
  stats:                    'בונה סטטיסטיקות',
  resources:                'שימושון',
  support:                  'תמיכה טכנית',
  'email-preferences':      'העדפות התראות מייל',
  'accessibility-statement':'הצהרת נגישות',
};

window.currentPageLabel = function currentPageLabel() {
  try {
    // route is in hash: #/programs, #/activity-detail/abc123
    const hash = (location.hash || '').replace(/^#\/?/, '');
    if (!hash) return 'לוח בקרה';
    const first = hash.split('/')[0] || 'dashboard';
    return window.PAGE_LABELS[first] || first;
  } catch { return '—'; }
};

// Default notification preferences
window.DEFAULT_EMAIL_PREFS = {
  onActivityApproved:     true,  // "הפעילות אושרה עקרונית"
  onActivityReturned:     true,  // "פעילות חזרה לתיקון"
  onAuditApproved:        true,  // "אשד אישרו"
  onAuditReturned:        true,  // "אשד החזירו"
  onPaymentSigned:        true,  // "הגזבר חתם"
  onTreasurerLink:        true,  // "נוצר קישור לגזבר"
  onPaymentApproved:      true,  // "אושר לתשלום"
  onForumMention:         false, // "מישהו הזכיר אותך בפורום"
  onForumReply:           false, // "תגובה בפוסט שלך"
  onForumNewPost:         false, // "פוסט חדש בפורום"
  onMeetingReminder:      true,  // "תזכורת למפגש מחר"
  weeklySummary:          false, // "סיכום שבועי"
};

// ───────────────────────────────────────────────
//  SupportPage — form to submit support tickets
// ───────────────────────────────────────────────
window.SupportPage = function SupportPage() {
  const { state, currentUser, submitSupportRequest } = window.useApp();
  const toast = window.useToast();
  const [category, setCategory] = uSS('general');
  const [subject, setSubject] = uSS('');
  const [description, setDescription] = uSS('');
  const [screenshot, setScreenshot] = uSS(null);
  const [submitted, setSubmitted] = uSS(null);
  // The page the user was on RIGHT BEFORE arriving at /support.
  // Captured from document.referrer equivalent via hash snapshot.
  const [pageContext, setPageContext] = uSS(() => {
    // Check sessionStorage for a "lastRoute" set by the Support sidebar click handler
    try {
      const saved = sessionStorage.getItem('haredim_support_from_route');
      if (saved) {
        sessionStorage.removeItem('haredim_support_from_route');
        return saved;
      }
    } catch {}
    return window.currentPageLabel();
  });
  const [pageHash, setPageHash] = uSS(() => {
    try { return sessionStorage.getItem('haredim_support_from_hash') || location.hash; } catch { return location.hash; }
  });
  const fileRef = uRS();

  const myTickets = (state.supportTickets || []).filter(t => t.userId === currentUser.id);
  const adminTickets = currentUser.role === 'admin' ? (state.supportTickets || []) : [];

  const categories = [
    { v: 'general',   l: 'כללי',              icon: 'Info',        color: '#64748b' },
    { v: 'bug',       l: 'באג / תקלה',         icon: 'AlertCircle', color: '#dc2626' },
    { v: 'feature',   l: 'בקשת פיצ\'ר',       icon: 'Sparkles',    color: '#7c3aed' },
    { v: 'access',    l: 'גישה / סיסמה',      icon: 'Shield',      color: '#d97706' },
    { v: 'question',  l: 'שאלה / הדרכה',      icon: 'Lightbulb',   color: '#2563eb' },
  ];

  const handleScreenshot = (file) => {
    const v = window.validateFile ? window.validateFile(file, 'image') : { ok: true };
    if (!v.ok) { toast.push({ type: 'error', title: 'הקובץ נדחה', message: v.error }); return; }
    const reader = new FileReader();
    reader.onload = e => setScreenshot(e.target.result);
    reader.readAsDataURL(file);
  };

  const submit = () => {
    if (!subject.trim()) { toast.push({ type: 'error', message: 'נושא הפנייה חובה' }); return; }
    if (!description.trim() || description.trim().length < 10) { toast.push({ type: 'error', message: 'יש לפרט את הבעיה (לפחות 10 תווים)' }); return; }
    const ticket = submitSupportRequest({
      category,
      subject: subject.trim(),
      description: description.trim(),
      screenshot,
      pageContext,           // Hebrew label of the page (e.g. "שיתוף קהילה")
      pageHash,              // Exact hash route (e.g. "#/community")
      url: location.href,    // Full URL at time of submission
      userAgent: navigator.userAgent,
      viewport: `${window.innerWidth}×${window.innerHeight}`,
    });
    setSubmitted(ticket);
    setSubject(''); setDescription(''); setScreenshot(null); setCategory('general');
    toast.push({ type: 'success', title: 'הפנייה נשלחה', message: 'נחזור אליך בימים הקרובים' });
  };

  return (
    <div className="animate-fade-in">
      <window.PageHeader
        title="תמיכה טכנית"
        subtitle="משהו לא עובד? שאלה? רעיון לשיפור? אנחנו כאן."
      />

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        {/* Form */}
        <div className="lg:col-span-2 space-y-4">
          {submitted ? (
            <div className="surface p-8 text-center animate-fade-in">
              <div className="w-20 h-20 rounded-full bg-emerald-100 text-emerald-600 mx-auto flex items-center justify-center mb-4">
                <window.Icon.CheckCircle size={42}/>
              </div>
              <h2 className="font-display font-black text-2xl mb-2">הפנייה נשלחה בהצלחה</h2>
              <p className="text-sm text-slate-600 mb-4">
                קיבלנו את הפנייה <strong>#{submitted.id.slice(0, 6)}</strong>.<br/>
                צוות התמיכה יחזור אליך למייל <strong dir="ltr">{currentUser.email}</strong> תוך 3 ימי עבודה.
              </p>
              <div className="flex items-center justify-center gap-2">
                <window.Button variant="primary" onClick={() => setSubmitted(null)}>פנייה נוספת</window.Button>
              </div>
            </div>
          ) : (
            <div className="surface p-6">
              <h3 className="font-display font-bold text-lg mb-1">שליחת פנייה חדשה</h3>
              <p className="text-sm text-slate-500 mb-4">תקבל התראה במייל מיד כשנטפל בזה</p>

              {/* Page context — clearly visible to both user and admin */}
              <window.Field label="מאיזה דף את/ה פונה?" help="נקלט אוטומטית מהדף בו היית. ניתן לשנות במידה ורלוונטי.">
                <div className="flex items-center gap-2 p-3 rounded-lg bg-brand-50 border border-brand-200">
                  <div className="w-9 h-9 rounded-lg bg-brand-600 text-white flex items-center justify-center shrink-0">
                    <window.Icon.MapPin size={16}/>
                  </div>
                  <div className="flex-1 min-w-0">
                    <select
                      value={pageContext}
                      onChange={e => {
                        const v = e.target.value;
                        setPageContext(v);
                        // If user picks a page from the dropdown, update the hash to match
                        const key = Object.keys(window.PAGE_LABELS).find(k => window.PAGE_LABELS[k] === v);
                        if (key) setPageHash(`#/${key}`);
                      }}
                      className="input bg-white"
                      aria-label="דף הפנייה"
                    >
                      {Object.values(window.PAGE_LABELS).map(lbl => (
                        <option key={lbl} value={lbl}>{lbl}</option>
                      ))}
                    </select>
                    <div className="text-[10px] text-brand-700 mt-1 font-mono ltr-num">
                      {pageHash || '#/'}
                    </div>
                  </div>
                  <button
                    type="button"
                    onClick={() => { setPageContext(window.currentPageLabel()); setPageHash(location.hash); toast.push({ message: 'עודכן לדף הנוכחי' }); }}
                    className="text-xs text-brand-700 hover:text-brand-900 font-bold px-2 py-1 hover:bg-white rounded focus-visible:ring-2 focus-visible:ring-brand-500"
                    title="השתמש בדף שאת/ה רואה עכשיו"
                  >
                    ↻ עכשיו
                  </button>
                </div>
              </window.Field>

              <window.Field label="קטגוריה" className="mt-4">
                <div className="grid grid-cols-2 md:grid-cols-5 gap-2">
                  {categories.map(c => {
                    const I = window.Icon[c.icon];
                    const on = category === c.v;
                    return (
                      <button
                        key={c.v}
                        type="button"
                        onClick={() => setCategory(c.v)}
                        className={`p-3 rounded-xl border-2 transition-all flex flex-col items-center gap-1 focus-visible:ring-2 focus-visible:ring-brand-500
                          ${on ? 'border-brand-600 bg-brand-50' : 'border-slate-200 hover:border-slate-300'}`}
                        style={on ? { borderColor: c.color, background: c.color + '10' } : {}}
                      >
                        <I size={20} style={{ color: on ? c.color : '#94a3b8' }}/>
                        <span className="text-xs font-bold" style={{ color: on ? c.color : '#475569' }}>{c.l}</span>
                      </button>
                    );
                  })}
                </div>
              </window.Field>

              <window.Field label="נושא" required className="mt-4">
                <input
                  value={subject}
                  onChange={e => setSubject(e.target.value)}
                  className="input"
                  placeholder="לדוגמה: לא מצליח להעלות חשבונית"
                  maxLength={120}
                />
              </window.Field>

              <window.Field label="פירוט הבעיה או השאלה" required className="mt-3" help="מה קרה? באיזה דף? מתי זה קרה?">
                <textarea
                  value={description}
                  onChange={e => setDescription(e.target.value)}
                  className="textarea"
                  style={{ minHeight: 140 }}
                  placeholder="נסיתי להעלות חשבונית בדף הפעילות 2.1, לחצתי על ״חשבוניות״, פתח לי את החלון, העלתי PDF של 3MB, לחצתי שמור — והתקבלה הודעה שגיאה..."
                  maxLength={2000}
                />
                <div className="text-[10px] text-slate-400 text-left mt-1 ltr-num">{description.length} / 2000</div>
              </window.Field>

              <window.Field label="צילום מסך (אופציונלי)" className="mt-3" help="עוזר לנו להבין את הבעיה מהר יותר">
                {screenshot ? (
                  <div className="relative">
                    <img src={screenshot} className="rounded-lg w-full max-h-60 object-contain bg-slate-100" alt=""/>
                    <button onClick={() => setScreenshot(null)} className="absolute top-2 left-2 w-8 h-8 rounded-full bg-red-500 text-white flex items-center justify-center">
                      <window.Icon.X size={14}/>
                    </button>
                  </div>
                ) : (
                  <button
                    type="button"
                    onClick={() => fileRef.current?.click()}
                    className="w-full drop-zone"
                  >
                    <window.Icon.Image size={24} className="mx-auto text-slate-400"/>
                    <div className="text-sm mt-2 text-slate-600">לחץ כדי להעלות צילום מסך</div>
                  </button>
                )}
                <input type="file" ref={fileRef} hidden accept="image/*" onChange={e => handleScreenshot(e.target.files[0])}/>
              </window.Field>

              <div className="flex items-center justify-between mt-5 pt-4 border-t border-slate-100">
                <div className="text-xs text-slate-500">
                  נחזור אליך ל-<strong dir="ltr">{currentUser.email}</strong>
                </div>
                <window.Button variant="primary" icon={<window.Icon.Send size={14}/>} onClick={submit}>שליחת פנייה</window.Button>
              </div>
            </div>
          )}

          {/* User's previous tickets */}
          {myTickets.length > 0 && (
            <div className="surface">
              <div className="p-4 border-b border-slate-100">
                <h3 className="font-display font-bold text-sm">הפניות שלי ({myTickets.length})</h3>
              </div>
              <div className="divide-y divide-slate-100">
                {myTickets.slice(0, 5).map(t => {
                  const cat = categories.find(c => c.v === t.category);
                  return (
                    <div key={t.id} className="p-3 flex items-center gap-3">
                      <div className="w-8 h-8 rounded-lg flex items-center justify-center shrink-0" style={{ background: (cat?.color || '#64748b') + '20', color: cat?.color }}>
                        {cat && window.Icon[cat.icon] && React.createElement(window.Icon[cat.icon], { size: 14 })}
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="font-semibold text-sm truncate">{t.subject}</div>
                        <div className="text-[11px] text-slate-500 flex items-center gap-1.5">
                          <span>#{t.id.slice(0,6)}</span>
                          <span>·</span>
                          <span>{new Date(t.createdAt).toLocaleDateString('he-IL')}</span>
                          {t.pageContext && (
                            <>
                              <span>·</span>
                              <span className="inline-flex items-center gap-0.5"><window.Icon.MapPin size={9}/> {t.pageContext}</span>
                            </>
                          )}
                        </div>
                      </div>
                      <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full ${
                        t.status === 'open'     ? 'bg-amber-100 text-amber-800' :
                        t.status === 'resolved' ? 'bg-emerald-100 text-emerald-800' :
                        'bg-slate-100 text-slate-700'
                      }`}>{t.status === 'open' ? 'פתוח' : t.status === 'resolved' ? 'נפתר' : t.status}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>

        {/* Sidebar info */}
        <aside className="space-y-4">
          <div className="surface p-5 bg-gradient-to-br from-brand-50 to-indigo-50 border border-brand-100">
            <div className="flex items-start gap-3">
              <div className="w-10 h-10 rounded-xl bg-brand-600 text-white flex items-center justify-center shrink-0">
                <window.Icon.Info size={18}/>
              </div>
              <div>
                <div className="font-display font-bold text-sm mb-1">איך אנחנו עוזרים</div>
                <ul className="text-xs text-slate-700 space-y-1 leading-relaxed">
                  <li>• זמן מענה ממוצע: <strong>3 ימי עסקים</strong></li>
                  <li>• באגים דחופים: <strong>עד 24 שעות</strong></li>
                  <li>• נחזור אליך במייל + פנייה תישמר במערכת</li>
                </ul>
              </div>
            </div>
          </div>

          <div className="surface p-5">
            <div className="font-display font-bold text-sm mb-2 flex items-center gap-2">
              <window.Icon.FileText size={14}/> דרכים נוספות לעזרה
            </div>
            <div className="space-y-2">
              <button onClick={() => window.useRouter().navigate('resources')} className="w-full text-right p-3 rounded-lg hover:bg-slate-50 border border-slate-100">
                <div className="font-bold text-sm">שימושון</div>
                <div className="text-xs text-slate-500">מדריכים, טפסים, תבניות</div>
              </button>
              <a href="tel:+972723389910" className="block p-3 rounded-lg hover:bg-slate-50 border border-slate-100" dir="ltr">
                <div className="font-bold text-sm text-right" dir="rtl">קו טלפוני</div>
                <div className="text-xs text-slate-500">072-338-9910 · א׳-ה׳ 9:00-17:00</div>
              </a>
              <a href="mailto:support@haredim.pmo.gov.il" className="block p-3 rounded-lg hover:bg-slate-50 border border-slate-100">
                <div className="font-bold text-sm">דוא"ל ישיר</div>
                <div className="text-xs text-slate-500" dir="ltr">support@haredim.pmo.gov.il</div>
              </a>
            </div>
          </div>

          {currentUser.role === 'admin' && adminTickets.length > 0 && (
            <div className="surface p-5">
              <div className="font-display font-bold text-sm mb-2 flex items-center gap-2">
                <window.Icon.Shield size={14}/> ניהול פניות ({adminTickets.length})
              </div>
              <div className="text-xs text-slate-500 mb-2">כל הפניות מהמערכת:</div>
              <div className="space-y-1 max-h-48 overflow-y-auto">
                {adminTickets.map(t => {
                  const user = state.users.find(u => u.id === t.userId);
                  return (
                    <div key={t.id} className="p-2 rounded border border-slate-100 text-xs">
                      <div className="font-bold truncate">{t.subject}</div>
                      <div className="text-slate-500">
                        {user?.name} · {new Date(t.createdAt).toLocaleDateString('he-IL')}
                      </div>
                      {t.pageContext && (
                        <div className="text-[10px] text-brand-700 mt-1 inline-flex items-center gap-0.5">
                          <window.Icon.MapPin size={9}/> {t.pageContext} <span className="text-slate-400 ltr-num">{t.pageHash}</span>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </aside>
      </div>
    </div>
  );
};

// ───────────────────────────────────────────────
//  EmailPreferences — render inline in SettingsPage
// ───────────────────────────────────────────────
window.EmailPreferencesPanel = function EmailPreferencesPanel() {
  const { state, currentUser, updateUserPrefs } = window.useApp();
  const toast = window.useToast();
  const prefs = { ...window.DEFAULT_EMAIL_PREFS, ...((state.userPrefs || {})[currentUser.id]?.email || {}) };

  const set = (key, value) => {
    const updated = { ...prefs, [key]: value };
    updateUserPrefs(currentUser.id, { email: updated });
  };

  const groups = [
    {
      title: 'פעילויות ואישורים',
      icon: 'CheckCircle',
      items: [
        { key: 'onActivityApproved', label: 'פעילות שלי אושרה עקרונית' },
        { key: 'onActivityReturned', label: 'פעילות שלי חזרה לתיקון' },
        { key: 'onAuditApproved',    label: 'אשד אישרו פעילות שלי' },
        { key: 'onAuditReturned',    label: 'אשד החזירו פעילות שלי' },
      ]
    },
    {
      title: 'תשלומים וחתימות',
      icon: 'Receipt',
      items: [
        { key: 'onPaymentSigned',    label: 'הגזבר חתם על דרישת תשלום' },
        { key: 'onTreasurerLink',    label: 'קישור חדש לגזבר נוצר' },
        { key: 'onPaymentApproved',  label: 'פעילות אושרה לתשלום' },
      ]
    },
    {
      title: 'פורום וקהילה',
      icon: 'FileText',
      items: [
        { key: 'onForumMention',    label: 'הזכירו אותי בפוסט' },
        { key: 'onForumReply',      label: 'תגובה חדשה בפוסט שלי' },
        { key: 'onForumNewPost',    label: 'פוסט חדש בפורום (daily digest)' },
      ]
    },
    {
      title: 'תזכורות ודוחות',
      icon: 'Clock',
      items: [
        { key: 'onMeetingReminder', label: 'תזכורת למפגש 24 שעות מראש' },
        { key: 'weeklySummary',     label: 'סיכום שבועי של הפעילות' },
      ]
    },
  ];

  const allOn = () => {
    const all = {};
    Object.keys(window.DEFAULT_EMAIL_PREFS).forEach(k => { all[k] = true; });
    updateUserPrefs(currentUser.id, { email: all });
    toast.push({ type: 'success', message: 'כל ההתראות מופעלות' });
  };
  const allOff = () => {
    const all = {};
    Object.keys(window.DEFAULT_EMAIL_PREFS).forEach(k => { all[k] = false; });
    updateUserPrefs(currentUser.id, { email: all });
    toast.push({ message: 'כל ההתראות כובו' });
  };

  return (
    <div className="surface p-5">
      <div className="flex items-start justify-between gap-3 mb-4">
        <div>
          <h3 className="font-display font-bold text-base mb-1 flex items-center gap-2">
            <window.Icon.Send size={16} className="text-brand-600"/> התראות במייל
          </h3>
          <p className="text-xs text-slate-500">בחר אילו אירועים יישלחו למייל שלך <strong dir="ltr">{currentUser.email}</strong></p>
        </div>
        <div className="flex items-center gap-1 shrink-0">
          <button onClick={allOn}  className="text-[11px] px-2 py-1 rounded bg-emerald-50 text-emerald-700 hover:bg-emerald-100 font-bold">הפעל הכל</button>
          <button onClick={allOff} className="text-[11px] px-2 py-1 rounded bg-slate-100 text-slate-600 hover:bg-slate-200 font-bold">כבה הכל</button>
        </div>
      </div>

      <div className="space-y-4">
        {groups.map(g => {
          const I = window.Icon[g.icon] || window.Icon.Info;
          return (
            <div key={g.title}>
              <div className="flex items-center gap-2 mb-2 text-xs font-bold text-slate-700 uppercase tracking-wide">
                <I size={12}/> {g.title}
              </div>
              <div className="space-y-1.5">
                {g.items.map(item => (
                  <label key={item.key} className="flex items-center justify-between p-2.5 rounded-lg border border-slate-100 hover:border-slate-200 hover:bg-slate-50 cursor-pointer">
                    <span className="text-sm">{item.label}</span>
                    <button
                      type="button"
                      role="switch"
                      aria-checked={!!prefs[item.key]}
                      onClick={() => set(item.key, !prefs[item.key])}
                      className={`w-11 h-6 rounded-full relative transition-colors focus-visible:ring-2 focus-visible:ring-brand-500 ${prefs[item.key] ? 'bg-brand-600' : 'bg-slate-300'}`}
                    >
                      <span className={`absolute top-0.5 w-5 h-5 rounded-full bg-white transition-all ${prefs[item.key] ? 'right-0.5' : 'right-5'}`}/>
                    </button>
                  </label>
                ))}
              </div>
            </div>
          );
        })}
      </div>

      <div className="mt-4 p-3 rounded-lg bg-amber-50 border border-amber-200 text-[11px] text-amber-800">
        <strong>הערה:</strong> תשתית ההתראות במייל תהיה פעילה במלואה לאחר חיבור ל-backend. כרגע מופעלים רק הלוגים הפנימיים — כל אירוע עם ✉ מציין שהמערכת הייתה שולחת מייל.
      </div>
    </div>
  );
};
