// SkinJourney Dashboard — Login + Register + PDF Report
const { useState: useS_aux } = React;

/* ── Auth Shell ─────────────────────────────────────────────────────── */
function AuthShell({ children }) {
  return (
    <div style={{
      minHeight: '100vh', display: 'grid', gridTemplateColumns: '1fr 1.1fr',
      background: 'var(--bg)',
    }}>
      {/* Form side (right in RTL — first column visually because of RTL) */}
      <div style={{
        padding: '48px 56px', display: 'flex', flexDirection: 'column',
        justifyContent: 'center', maxWidth: 520, width: '100%', margin: '0 auto',
      }}>
        {children}
      </div>

      {/* Brand panel */}
      <div style={{
        background: 'linear-gradient(160deg, var(--sage-600) 0%, var(--sage-800) 100%)',
        color: 'white', position: 'relative', overflow: 'hidden',
        display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
        padding: 56,
      }}>
        {/* Organic blobs */}
        <div style={{
          position: 'absolute', top: -80, insetInlineEnd: -80, width: 380, height: 380,
          borderRadius: '58% 42% 60% 40% / 45% 58% 42% 55%',
          background: 'rgba(232,165,152,0.18)', filter: 'blur(40px)',
        }} />
        <div style={{
          position: 'absolute', bottom: -120, insetInlineStart: -120, width: 460, height: 460,
          borderRadius: '52% 48% 58% 42% / 55% 42% 58% 45%',
          background: 'rgba(168,197,184,0.22)', filter: 'blur(60px)',
        }} />

        <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{
            width: 40, height: 40, borderRadius: 12,
            background: 'rgba(255,255,255,0.12)', border: '1px solid rgba(255,255,255,0.18)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="leaf" size={20} />
          </div>
          <span className="wordmark" style={{ fontSize: 26, color: 'white' }}>SkinJourney</span>
        </div>

        <div style={{ position: 'relative', maxWidth: 480 }}>
          <p style={{
            margin: 0, fontSize: 11, fontWeight: 700,
            letterSpacing: 1.2, textTransform: 'uppercase',
            color: 'rgba(255,255,255,0.5)',
          }}>
            מסע העור · לוח המטפלים
          </p>
          <h2 style={{
            margin: '12px 0 16px', fontSize: 40, fontWeight: 700,
            lineHeight: 1.18, letterSpacing: '-0.5px',
          }}>
            תיעוד עדין של המסע — כדי שתוכלי להתמקד במה שחשוב באמת.
          </h2>
          <p style={{ margin: 0, fontSize: 16, color: 'rgba(255,255,255,0.78)', lineHeight: 1.65 }}>
            עקבי אחרי ההתקדמות של המטופלות שלך לאורך שבועות וחודשים, נהלי תורים, וצרי דוחות בלחיצה אחת.
          </p>
        </div>

        <div style={{ position: 'relative', display: 'flex', gap: 24, fontSize: 12, color: 'rgba(255,255,255,0.5)' }}>
          <span>פרטיות מקצועית</span>
          <span>·</span>
          <span>הצפנה מקצה לקצה</span>
          <span>·</span>
          <span>HIPAA-aware</span>
        </div>
      </div>
    </div>
  );
}

function LoginScreen({ navigate }) {
  const [email, setEmail] = useS_aux('');
  const [pwd, setPwd] = useS_aux('');
  const [loading, setLoading] = useS_aux(false);

  const submit = (e) => {
    e && e.preventDefault();
    setLoading(true);
    setTimeout(() => { setLoading(false); navigate({ name: 'overview' }); }, 700);
  };

  return (
    <AuthShell>
      <div className="fade-up">
        <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--sage-700)', letterSpacing: 1.2, textTransform: 'uppercase' }}>
          ברוכה השבה
        </span>
        <h1 style={{ margin: '12px 0 8px', fontSize: 36, fontWeight: 700, letterSpacing: '-0.5px' }}>
          כניסה לחשבון
        </h1>
        <p style={{ margin: '0 0 32px', fontSize: 14, color: 'var(--text-tertiary)' }}>
          אין לך עדיין חשבון?{' '}
          <button onClick={() => navigate({ name: 'register' })}
                  style={{ background: 'none', border: 'none', color: 'var(--sage-700)', fontWeight: 700, cursor: 'pointer', fontSize: 14 }}>
            הירשמי עכשיו
          </button>
        </p>

        <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="field">
            <label className="field-label">כתובת אימייל</label>
            <input className="input" type="email" value={email} onChange={(e) => setEmail(e.target.value)}
                   placeholder="you@clinic.co.il" dir="ltr" style={{ direction: 'ltr', textAlign: 'start' }} />
          </div>
          <div className="field">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <label className="field-label">סיסמה</label>
              <button type="button" style={{ background: 'none', border: 'none', color: 'var(--sage-700)', fontSize: 12, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap' }}>
                שכחת סיסמה?
              </button>
            </div>
            <input className="input" type="password" value={pwd} onChange={(e) => setPwd(e.target.value)} placeholder="••••••••" />
          </div>

          <Button kind="primary" size="lg" type="submit" disabled={loading} style={{ marginTop: 8 }}>
            {loading ? (
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                <span style={{
                  width: 14, height: 14, borderRadius: '50%',
                  border: '2px solid rgba(255,255,255,0.3)', borderTopColor: 'white',
                  animation: 'spin 0.7s linear infinite', display: 'inline-block',
                }} />
                מתחברת…
              </span>
            ) : 'כניסה לחשבון'}
          </Button>
        </form>

        <div style={{ marginTop: 32, padding: 16, background: 'var(--sand-100)', borderRadius: 12, fontSize: 12, color: 'var(--text-tertiary)', textAlign: 'center' }}>
          הפרטים שלך נשמרים מוצפנים. רק את רואה את הנתונים של המטופלות שלך.
        </div>
      </div>
    </AuthShell>
  );
}

function RegisterScreen({ navigate }) {
  const [step, setStep] = useS_aux(1);
  const [form, setForm] = useS_aux({ name: '', clinic: '', email: '', pwd: '' });
  const set = (k, v) => setForm({ ...form, [k]: v });

  const submit = (e) => {
    e && e.preventDefault();
    setStep(2);
    setTimeout(() => navigate({ name: 'overview' }), 2400);
  };

  if (step === 2) {
    return (
      <AuthShell>
        <div className="fade-up" style={{ textAlign: 'center' }}>
          <div style={{
            width: 84, height: 84, borderRadius: 24,
            background: 'var(--sage-50)', color: 'var(--sage-700)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            margin: '0 auto 20px',
          }}>
            <Icon name="check" size={36} />
          </div>
          <h1 style={{ margin: '0 0 12px', fontSize: 32, fontWeight: 700 }}>ברוכה הבאה ל-SkinJourney</h1>
          <p style={{ margin: '0 0 32px', fontSize: 15, color: 'var(--text-secondary)' }}>
            החשבון נוצר. הקוד שלך מוכן להזמין מטופלות.
          </p>
          <div style={{
            padding: '24px 32px', background: 'linear-gradient(160deg, var(--sage-50), var(--sand-100))',
            border: '1px solid var(--sage-200)', borderRadius: 18,
            display: 'inline-block', textAlign: 'start',
          }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-tertiary)', letterSpacing: 0.6, textTransform: 'uppercase' }}>
              קוד ההצטרפות שלך
            </div>
            <div className="wordmark tabular" style={{ fontSize: 42, color: 'var(--sage-700)', direction: 'ltr', letterSpacing: 4, lineHeight: 1.1, marginTop: 6 }}>
              SJ-{Math.random().toString(36).slice(2, 8).toUpperCase()}
            </div>
          </div>
          <p style={{ marginTop: 24, fontSize: 13, color: 'var(--text-tertiary)' }}>מעבירה אותך ללוח הבקרה…</p>
        </div>
      </AuthShell>
    );
  }

  return (
    <AuthShell>
      <div className="fade-up">
        <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--sage-700)', letterSpacing: 1.2, textTransform: 'uppercase' }}>
          הרשמה למרפאות
        </span>
        <h1 style={{ margin: '12px 0 8px', fontSize: 36, fontWeight: 700, letterSpacing: '-0.5px' }}>
          יצירת חשבון
        </h1>
        <p style={{ margin: '0 0 32px', fontSize: 14, color: 'var(--text-tertiary)' }}>
          יש כבר חשבון?{' '}
          <button onClick={() => navigate({ name: 'login' })}
                  style={{ background: 'none', border: 'none', color: 'var(--sage-700)', fontWeight: 700, cursor: 'pointer', fontSize: 14 }}>
            כניסה
          </button>
        </p>

        <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div className="field">
              <label className="field-label">שם פרטי</label>
              <input className="input" value={form.name} onChange={(e) => set('name', e.target.value)} placeholder="שירה" />
            </div>
            <div className="field">
              <label className="field-label">שם המרפאה</label>
              <input className="input" value={form.clinic} onChange={(e) => set('clinic', e.target.value)} placeholder="מרפאת אור" />
            </div>
          </div>
          <div className="field">
            <label className="field-label">כתובת אימייל</label>
            <input className="input" type="email" value={form.email} onChange={(e) => set('email', e.target.value)} dir="ltr" style={{ direction: 'ltr' }} placeholder="you@clinic.co.il" />
          </div>
          <div className="field">
            <label className="field-label">סיסמה</label>
            <input className="input" type="password" value={form.pwd} onChange={(e) => set('pwd', e.target.value)} placeholder="לפחות 8 תווים" />
            <span className="field-help">לפחות 8 תווים, כולל אות גדולה ומספר</span>
          </div>

          <label style={{ display: 'flex', alignItems: 'flex-start', gap: 8, fontSize: 13, color: 'var(--text-secondary)', cursor: 'pointer' }}>
            <input type="checkbox" defaultChecked style={{ marginTop: 3 }} />
            <span>אני מאשרת את <button type="button" style={{ background: 'none', border: 'none', color: 'var(--sage-700)', textDecoration: 'underline', padding: 0, fontSize: 13, cursor: 'pointer' }}>תנאי השימוש</button> ו-<button type="button" style={{ background: 'none', border: 'none', color: 'var(--sage-700)', textDecoration: 'underline', padding: 0, fontSize: 13, cursor: 'pointer' }}>מדיניות הפרטיות</button></span>
          </label>

          <Button kind="primary" size="lg" type="submit" style={{ marginTop: 8 }}>יצירת חשבון</Button>
        </form>
      </div>
    </AuthShell>
  );
}

/* ── PDF Report (print-perfect, A4) ─────────────────────────────────── */
function ReportScreen({ route, navigate }) {
  const patient = SJ_DATA.byId(route.id) || SJ_DATA.PATIENTS[0];
  const timeline = SJ_DATA.buildTimeline(patient);
  const front = timeline.filter((c) => c.angle === 'front' && c.available);
  const right = timeline.filter((c) => c.angle === 'right' && c.available);
  const left = timeline.filter((c) => c.angle === 'left' && c.available);

  const pair = (arr) => arr.length >= 2 ? [arr[0], arr[arr.length - 1]] : [arr[0], arr[0]];

  return (
    <div style={{ minHeight: '100vh', background: 'var(--sand-200)', padding: 32 }}>
      {/* Toolbar (hidden in print) */}
      <div className="no-print" style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        maxWidth: 820, margin: '0 auto 24px', padding: '12px 20px',
        background: 'var(--surface-elevated)', borderRadius: 999,
        boxShadow: 'var(--elev-2)',
      }}>
        <Button kind="ghost" icon="arrow_right" onClick={() => navigate({ name: 'patient', id: patient.id })}>
          חזרה לתיק המטופלת
        </Button>
        <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-secondary)' }}>תצוגה מקדימה של הדוח</span>
        <Button kind="accent" icon="pdf" onClick={() => window.print()}>הדפס / שמרי PDF</Button>
      </div>

      {/* The A4 page itself */}
      <div className="report-page" style={{
        maxWidth: 820, margin: '0 auto',
        background: 'white', boxShadow: 'var(--elev-3)',
        padding: 56, borderRadius: 4,
        color: '#161D1F',
      }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', borderBottom: '2px solid var(--sage-600)', paddingBottom: 20 }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <Icon name="leaf" size={22} style={{ color: 'var(--sage-700)' }} />
              <span className="wordmark" style={{ fontSize: 26, color: 'var(--sage-700)' }}>SkinJourney</span>
            </div>
            <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginTop: 4 }}>
              דוח התקדמות · {SJ_DATA.PRACTITIONER.clinic_name}
            </div>
          </div>
          <div style={{ textAlign: 'end' }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-tertiary)', letterSpacing: 0.4, textTransform: 'uppercase' }}>תאריך</div>
            <div style={{ fontSize: 14, fontWeight: 600 }}>{SJ_DATA.formatHebFull(SJ_DATA.NOW)}</div>
          </div>
        </div>

        {/* Patient summary */}
        <div style={{ padding: '24px 0 8px' }}>
          <h1 style={{ margin: 0, fontSize: 30, fontWeight: 700, letterSpacing: '-0.4px' }}>{patient.name}</h1>
          <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
            <Chip kind="neutral">בת {patient.age}</Chip>
            <Chip>עור {patient.skin_label}</Chip>
            {patient.focus_labels.map((f) => <Chip key={f} kind="coral">{f}</Chip>)}
          </div>
        </div>

        {/* Summary grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, margin: '20px 0 32px' }}>
          <div style={{ background: 'var(--surface-sunken)', borderRadius: 12, padding: '14px 18px' }}>
            <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--text-tertiary)', letterSpacing: 0.4, textTransform: 'uppercase' }}>שבועות מעקב</div>
            <div className="tabular" style={{ fontSize: 26, fontWeight: 700, marginTop: 2 }}>{patient.weeks_tracked}</div>
          </div>
          <div style={{ background: 'var(--surface-sunken)', borderRadius: 12, padding: '14px 18px' }}>
            <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--text-tertiary)', letterSpacing: 0.4, textTransform: 'uppercase' }}>סך תמונות</div>
            <div className="tabular" style={{ fontSize: 26, fontWeight: 700, marginTop: 2 }}>{patient.photo_count}</div>
          </div>
          <div style={{ background: 'var(--surface-sunken)', borderRadius: 12, padding: '14px 18px' }}>
            <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--text-tertiary)', letterSpacing: 0.4, textTransform: 'uppercase' }}>עקביות</div>
            <div className="tabular" style={{ fontSize: 26, fontWeight: 700, marginTop: 2 }}>{Math.round((patient.photo_count / (patient.weeks_tracked * 3)) * 100)}%</div>
          </div>
        </div>

        {/* Before/After per angle */}
        <h2 style={{ fontSize: 18, fontWeight: 700, margin: '0 0 16px' }}>השוואה לפני / אחרי</h2>
        {[['front', 'חזית', pair(front)], ['right', 'צד ימין', pair(right)], ['left', 'צד שמאל', pair(left)]].map(([angle, label, pp]) => (
          <div key={angle} style={{ marginBottom: 20 }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-tertiary)', letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 8 }}>
              {label}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <div>
                <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginBottom: 4 }}>לפני · {pp[0]?.date_short}</div>
                <PhotoSlot angle={angle} date={pp[0]?.date_short} week={pp[0]?.week} available size="md" style={{ width: '100%', height: 220 }} />
              </div>
              <div>
                <div style={{ fontSize: 11, color: 'var(--sage-700)', fontWeight: 700, marginBottom: 4 }}>אחרי · {pp[1]?.date_short}</div>
                <PhotoSlot angle={angle} date={pp[1]?.date_short} week={pp[1]?.week} available size="md" style={{ width: '100%', height: 220 }} />
              </div>
            </div>
          </div>
        ))}

        {/* Notes */}
        {SJ_DATA.NOTES[patient.id]?.length > 0 && (
          <div style={{ marginTop: 32, pageBreakInside: 'avoid' }}>
            <h2 style={{ fontSize: 18, fontWeight: 700, margin: '0 0 12px' }}>סיכום קליני</h2>
            {SJ_DATA.NOTES[patient.id].slice(0, 3).map((n) => (
              <div key={n.id} style={{ padding: '12px 0', borderBottom: '1px solid var(--border-subtle)' }}>
                <div style={{ fontSize: 11, color: 'var(--text-tertiary)', fontWeight: 600, marginBottom: 4 }}>
                  {SJ_DATA.formatHebFull(n.date)}{n.treatment ? ` · ${n.treatment}` : ''}
                </div>
                <p style={{ margin: 0, fontSize: 13, lineHeight: 1.55 }}>{n.body}</p>
              </div>
            ))}
          </div>
        )}

        {/* Footer */}
        <div style={{
          marginTop: 40, paddingTop: 20,
          borderTop: '1px solid var(--border-subtle)',
          display: 'flex', justifyContent: 'space-between',
          fontSize: 11, color: 'var(--text-tertiary)',
        }}>
          <span>הופק באמצעות SkinJourney · מסע העור</span>
          <span>{SJ_DATA.PRACTITIONER.name} · {SJ_DATA.PRACTITIONER.clinic_name}</span>
        </div>
      </div>

      <style>{`
        @media print {
          @page { size: A4; margin: 0; }
          body { background: white !important; }
          .no-print { display: none !important; }
          .report-page { box-shadow: none !important; max-width: none !important; }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { LoginScreen, RegisterScreen, ReportScreen });
