// SkinJourney Dashboard — Settings
const { useState: useS_set } = React;

function SettingsRow({ label, hint, children }) {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '280px 1fr', gap: 32,
      padding: '24px 0',
      borderBottom: '1px solid var(--border-subtle)',
      alignItems: 'flex-start',
    }}>
      <div>
        <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text-primary)' }}>{label}</div>
        {hint && <div style={{ marginTop: 4, fontSize: 12, color: 'var(--text-tertiary)', lineHeight: 1.55 }}>{hint}</div>}
      </div>
      <div>{children}</div>
    </div>
  );
}

function QRPlaceholder({ size = 160 }) {
  // Pure CSS abstract QR placeholder
  const cells = [];
  // Deterministic pseudo-random
  const seed = 'SJ-7K2M9P';
  for (let r = 0; r < 7; r++) {
    for (let c = 0; c < 7; c++) {
      const on = ((seed.charCodeAt((r * 7 + c) % seed.length) * (r + 1) * (c + 1)) % 3) === 0;
      cells.push({ r, c, on });
    }
  }
  return (
    <div style={{
      width: size, height: size, padding: 14,
      background: 'white', border: '1px solid var(--border-default)',
      borderRadius: 16, position: 'relative',
    }}>
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)',
        gap: 2, width: '100%', height: '100%',
      }}>
        {cells.map((cell, i) => (
          <div key={i} style={{
            background: cell.on ? 'var(--sage-700)' : 'transparent',
            borderRadius: 2,
          }} />
        ))}
      </div>
      {/* Corner markers */}
      {[[8, 8], [8, size - 32], [size - 32, 8]].map(([t, l], i) => (
        <div key={i} style={{
          position: 'absolute', top: t, left: l,
          width: 24, height: 24, border: '3px solid var(--sage-700)',
          borderRadius: 4, background: 'white',
        }}>
          <div style={{ width: 8, height: 8, background: 'var(--sage-700)', margin: 5, borderRadius: 1 }} />
        </div>
      ))}
      {/* Brand leaf at center */}
      <div style={{
        position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)',
        width: 28, height: 28, borderRadius: 8,
        background: 'white', border: '2px solid var(--sage-700)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: 'var(--sage-700)',
      }}>
        <Icon name="leaf" size={14} />
      </div>
    </div>
  );
}

function SettingsScreen({ navigate }) {
  const p = SJ_DATA.PRACTITIONER;
  const toast = useToast();
  const [tab, setTab] = useS_set('clinic');
  const [name, setName] = useS_set(p.name);
  const [clinic, setClinic] = useS_set(p.clinic_name);
  const [email, setEmail] = useS_set(p.email);
  const [notif, setNotif] = useS_set({ push: true, email: true, weekly: false });

  return (
    <div className="screen content-scroll">
      <PageHeader title="הגדרות" subtitle="ניהול המרפאה והחשבון שלך" />

      <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr', gap: 32, alignItems: 'start' }}>
        {/* Side tabs */}
        <nav style={{ display: 'flex', flexDirection: 'column', gap: 2, position: 'sticky', top: 88 }}>
          {[
            { k: 'clinic', label: 'פרופיל המרפאה', icon: 'leaf' },
            { k: 'invite', label: 'קוד הצטרפות', icon: 'qr' },
            { k: 'account', label: 'חשבון וכניסה', icon: 'patients' },
            { k: 'notifications', label: 'התראות', icon: 'bell' },
          ].map((t) => (
            <button key={t.k} onClick={() => setTab(t.k)}
              className="rail-item" data-active={tab === t.k}
              style={{ background: tab === t.k ? 'var(--sage-50)' : 'transparent' }}>
              <Icon name={t.icon} size={16} className="icon" />
              <span className="label">{t.label}</span>
            </button>
          ))}
        </nav>

        <div>
          {tab === 'clinic' && (
            <Card>
              <h2 style={{ margin: '0 0 6px', fontSize: 20, fontWeight: 700 }}>פרופיל המרפאה</h2>
              <p style={{ margin: '0 0 8px', fontSize: 13, color: 'var(--text-tertiary)' }}>
                המידע הזה מופיע למטופלות באפליקציה
              </p>
              <div style={{ marginTop: 16 }}>
                <SettingsRow label="שם המטפלת" hint="מופיע בפגישות ובדוחות ההתקדמות">
                  <input className="input" value={name} onChange={(e) => setName(e.target.value)} />
                </SettingsRow>
                <SettingsRow label="שם המרפאה" hint="מופיע בכותרת ובדוחות PDF">
                  <input className="input" value={clinic} onChange={(e) => setClinic(e.target.value)} />
                </SettingsRow>
                <SettingsRow label="לוגו המרפאה" hint="מופיע בראש כל דוח PDF (אופציונלי)">
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                    <div style={{
                      width: 64, height: 64, borderRadius: 14,
                      background: 'var(--grad-sage)', color: 'white',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>
                      <Icon name="leaf" size={24} />
                    </div>
                    <Button kind="secondary" icon="upload">העלאת תמונה</Button>
                  </div>
                </SettingsRow>
              </div>
              <div style={{ display: 'flex', gap: 8, marginTop: 24 }}>
                <Button kind="primary" icon="check" onClick={() => toast.push('פרטי המרפאה נשמרו')}>שמרי שינויים</Button>
                <Button kind="ghost">ביטול</Button>
              </div>
            </Card>
          )}

          {tab === 'invite' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
              <Card>
                <h2 style={{ margin: '0 0 6px', fontSize: 20, fontWeight: 700 }}>קוד ההצטרפות שלך</h2>
                <p style={{ margin: '0 0 24px', fontSize: 13, color: 'var(--text-tertiary)' }}>
                  זה הקוד שמטופלות חדשות מזינות באפליקציה כדי להתחבר אלייך
                </p>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 32, alignItems: 'center' }}>
                  <div>
                    <div style={{
                      padding: '24px 28px',
                      background: 'linear-gradient(160deg, var(--sage-50) 0%, var(--sand-100) 100%)',
                      border: '1px solid var(--sage-200)',
                      borderRadius: 16,
                    }}>
                      <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-tertiary)', letterSpacing: 0.6, textTransform: 'uppercase' }}>
                        הקוד שלך
                      </div>
                      <div className="wordmark tabular" style={{ fontSize: 44, color: 'var(--sage-700)', direction: 'ltr', letterSpacing: 4, lineHeight: 1.1, margin: '8px 0' }}>
                        {p.invite_code}
                      </div>
                    </div>
                    <div style={{ display: 'flex', gap: 8, marginTop: 16, flexWrap: 'wrap' }}>
                      <Button kind="primary" icon="copy" onClick={() => toast.push('הקוד הועתק')}>העתיקי קוד</Button>
                      <Button kind="secondary" icon="share">שתפי בוואטסאפ</Button>
                      <Button kind="secondary" icon="download">הורד QR</Button>
                    </div>
                  </div>
                  <QRPlaceholder size={180} />
                </div>
              </Card>

              <Card>
                <h3 style={{ margin: '0 0 14px', fontSize: 16, fontWeight: 700 }}>הודעה מוכנה לשליחה</h3>
                <div style={{
                  background: 'var(--surface-sunken)', borderRadius: 12,
                  padding: '16px 18px', fontSize: 14, color: 'var(--text-secondary)', lineHeight: 1.7,
                }}>
                  היי 👋 שמחה שאת מצטרפת ל-SkinJourney — האפליקציה שבה תעדי את מסע העור שלך ותראי איך הוא משתפר.<br/>
                  הורידי את האפליקציה, פתחי הגדרות {'>'} ״חיבור למטפל/ת״ והזיני את הקוד: <strong className="ltr-run" style={{ color: 'var(--sage-700)' }}>{p.invite_code}</strong>.<br/>
                  אם יש שאלות אני כאן 💚
                </div>
                <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
                  <Button kind="secondary" icon="copy" onClick={() => toast.push('ההודעה הועתקה')}>העתיקי</Button>
                  <Button kind="ghost" icon="edit">ערכי</Button>
                </div>
              </Card>

              <Card>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16 }}>
                  <div style={{ flex: 1 }}>
                    <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>החלפת קוד</h3>
                    <p style={{ margin: '6px 0 0', fontSize: 13, color: 'var(--text-tertiary)', lineHeight: 1.55 }}>
                      קוד חדש לא ינתק מטופלות קיימות, אבל הקוד הישן יפסיק לפעול עבור חיבורים חדשים.
                    </p>
                  </div>
                  <Button kind="ghost" size="sm">צרי קוד חדש</Button>
                </div>
              </Card>
            </div>
          )}

          {tab === 'account' && (
            <Card>
              <h2 style={{ margin: '0 0 6px', fontSize: 20, fontWeight: 700 }}>חשבון וכניסה</h2>
              <p style={{ margin: 0, fontSize: 13, color: 'var(--text-tertiary)' }}>פרטי הכניסה והאבטחה שלך</p>

              <div style={{ marginTop: 16 }}>
                <SettingsRow label="כתובת אימייל" hint="משמשת לכניסה לחשבון">
                  <input className="input" value={email} onChange={(e) => setEmail(e.target.value)} dir="ltr" style={{ direction: 'ltr' }} />
                </SettingsRow>
                <SettingsRow label="סיסמה" hint="הסיסמה האחרונה שונתה לפני 3 חודשים">
                  <Button kind="secondary" icon="edit">שינוי סיסמה</Button>
                </SettingsRow>
                <SettingsRow label="אימות דו-שלבי" hint="הגנה נוספת על פרטי המטופלות שלך">
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                    <Chip kind="success" dot>פעיל</Chip>
                    <Button kind="ghost" size="sm">ניהול</Button>
                  </div>
                </SettingsRow>
                <SettingsRow label="פעולות אזור מסוכן" hint="מחיקת חשבון לצמיתות. פעולה לא הפיכה.">
                  <Button kind="danger" icon="trash">מחיקת חשבון</Button>
                </SettingsRow>
              </div>
            </Card>
          )}

          {tab === 'notifications' && (
            <Card>
              <h2 style={{ margin: '0 0 6px', fontSize: 20, fontWeight: 700 }}>התראות</h2>
              <p style={{ margin: 0, fontSize: 13, color: 'var(--text-tertiary)' }}>מתי לקבל הודעה?</p>

              <div style={{ marginTop: 16 }}>
                {[
                  { k: 'push', label: 'התראות דחיפה', hint: 'בקשות תור חדשות, ביטולים' },
                  { k: 'email', label: 'אימייל יומי', hint: 'סיכום הבוקר של היום' },
                  { k: 'weekly', label: 'דוח שבועי', hint: 'סיכום שבועי של הפעילות במרפאה' },
                ].map((n) => (
                  <SettingsRow key={n.k} label={n.label} hint={n.hint}>
                    <button onClick={() => setNotif({ ...notif, [n.k]: !notif[n.k] })}
                      style={{
                        width: 44, height: 24, borderRadius: 999,
                        background: notif[n.k] ? 'var(--sage-600)' : 'var(--sand-400)',
                        border: 'none', position: 'relative', cursor: 'pointer',
                        transition: 'background var(--dur-quick) var(--ease-standard)',
                      }}>
                      <span style={{
                        position: 'absolute', top: 3, insetInlineStart: notif[n.k] ? 23 : 3,
                        width: 18, height: 18, borderRadius: '50%',
                        background: 'white', boxShadow: 'var(--elev-1)',
                        transition: 'inset-inline-start var(--dur-standard) var(--ease-emphasized)',
                      }} />
                    </button>
                  </SettingsRow>
                ))}
              </div>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}

window.SettingsScreen = SettingsScreen;
