// ScrollJob — Seeker utility screens
// Saved Jobs, View History, Email History, Settings
// Uses SJ tokens, Header/Footer/SidebarNav from earlier scripts.

// Helper: page wrapper with sidebar
function SeekerPage({ activeKey, title, subtitle, children, sourceLabel }) {
  return (
    <div style={{ background: '#fff', fontFamily: SJ.font, color: SJ.ink2, minHeight: '100%' }}>
      <Header active="" />
      <main style={{ maxWidth: 1200, margin: '0 auto', padding: '40px 28px 0' }}>
        <div style={{ display: 'flex', gap: 32, alignItems: 'flex-start' }}>
          <SidebarNav mode="seeker" activeKey={activeKey} user={{ name: 'Olena Kovalenko', email: 'olena.k@example.com', initials: 'OK' }} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <h2 style={{ fontSize: 26, fontWeight: 700, color: SJ.ink, margin: '0 0 6px', letterSpacing: '-0.02em' }}>{title}</h2>
            <p style={{ color: SJ.muted, margin: '0 0 22px', fontSize: 15 }}>{subtitle}</p>
            {sourceLabel && (
              <div style={{
                display: 'inline-flex', alignItems: 'center', gap: 8,
                padding: '8px 12px', marginBottom: 18,
                background: '#ecfeff', color: '#155e75', border: '1px solid #a5f3fc',
                borderRadius: 999, fontSize: 13, fontWeight: 600,
              }}>📊 {sourceLabel}</div>
            )}
            {children}
          </div>
        </div>
      </main>
      <Footer />
    </div>
  );
}

// Inline mini job card used in saved / history lists
function MiniJobCard({ job, removeLabel, removeTone, footer }) {
  return (
    <div style={{
      background: '#fff', border: `1px solid ${SJ.line}`, borderRadius: 16,
      padding: 22, marginBottom: 14, boxShadow: '0 1px 3px rgba(0,0,0,0.05)',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16 }}>
        <div style={{ flex: 1, minWidth: 0, display: 'flex', gap: 14 }}>
          <div style={{
            width: 44, height: 44, borderRadius: 12,
            background: `linear-gradient(135deg, ${SJ.blueRing}, ${SJ.blueSoft})`,
            color: SJ.blueDark, display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 18, fontWeight: 800, flexShrink: 0,
          }}>{job.mark}</div>
          <div style={{ minWidth: 0 }}>
            <a style={{ fontSize: 17, fontWeight: 700, color: SJ.ink2, textDecoration: 'none' }}>{job.title}</a>
            <div style={{ fontSize: 14, fontWeight: 600, color: SJ.blue, marginTop: 4 }}>{job.company}</div>
            <div style={{ fontSize: 13.5, color: SJ.muted, marginTop: 6 }}>
              {job.location}{job.type && <> · {job.type}</>}
            </div>
            {job.desc && (
              <p style={{ color: '#4b5563', margin: '10px 0 0', fontSize: 13.5, lineHeight: 1.6 }}>{job.desc}</p>
            )}
            {footer && <div style={{ fontSize: 12.5, color: SJ.muted, marginTop: 10 }}>{footer}</div>}
          </div>
        </div>
        {removeLabel && (
          <button style={{
            padding: '8px 16px', border: `1px solid ${removeTone === 'red' ? SJ.red : SJ.line}`,
            background: '#fff', color: removeTone === 'red' ? SJ.red : SJ.text,
            borderRadius: 8, fontSize: 13, fontWeight: 500,
            whiteSpace: 'nowrap', cursor: 'pointer', fontFamily: SJ.font,
          }}>{removeLabel}</button>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// SAVED JOBS
// ─────────────────────────────────────────────────────────────────────────
function SavedJobsScreen() {
  const jobs = [
    { mark: 'M', title: 'Senior Python Engineer', company: 'Monzo Bank', location: 'London, UK', type: 'Full-time',
      desc: 'Platform team building the rails of a digital bank — async-first Python services, sensible PostgreSQL.', savedAgo: '2 hours' },
    { mark: 'W', title: 'Staff Product Designer', company: 'Wise', location: 'London, UK · Hybrid', type: 'Full-time',
      desc: 'Own end-to-end design for cross-border money movement. Ship in 6-week cycles.', savedAgo: '5 hours' },
    { mark: 'R', title: 'Engineering Manager · Search', company: 'Revolut', location: 'Remote, UK', type: 'Full-time',
      desc: 'Lead a small autonomous pod working on consumer search and discovery.', savedAgo: 'Yesterday' },
    { mark: 'C', title: 'Senior Python Engineer', company: 'Cleo AI', location: 'London, UK', type: 'Full-time',
      desc: 'Reduce toil and keep the AI inference infrastructure fast and reliable.', savedAgo: '2 days' },
    { mark: 'O', title: 'Frontend Engineer (React)', company: 'Octopus Energy', location: 'Remote, UK', type: 'Full-time',
      desc: 'Build customer-facing experiences in React + TypeScript focused on accessibility.', savedAgo: '4 days' },
    { mark: 'B', title: 'Data Scientist — Pricing', company: 'Bulb', location: 'Remote, UK', type: 'Full-time',
      desc: 'Build pricing models balancing fairness for customers with business sustainability.', savedAgo: '1 week' },
  ];
  return (
    <SeekerPage activeKey="saved" title="Saved Jobs" subtitle="Jobs you've saved for later — 6 total · 2 new since yesterday">
      {/* Quick filters */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 20, flexWrap: 'wrap', alignItems: 'center' }}>
        {[['All', 6, true], ['Remote', 4], ['London', 4], ['Last 7 days', 5]].map(([t, n, on]) => (
          <button key={t} style={{
            padding: '8px 14px', borderRadius: 999, fontSize: 13, fontWeight: 600,
            border: `1px solid ${on ? SJ.blue : SJ.line}`,
            background: on ? SJ.blueSoft : '#fff',
            color: on ? SJ.blueDark : SJ.text,
            cursor: 'pointer', fontFamily: SJ.font,
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>
            {t} <span style={{ fontSize: 11, opacity: 0.7 }}>{n}</span>
          </button>
        ))}
        <span style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 8, color: SJ.muted, fontSize: 14 }}>
          Sort by
          <select defaultValue="recent" style={{
            padding: '7px 12px', border: `1px solid ${SJ.line}`, borderRadius: 8,
            fontSize: 13, color: SJ.ink, background: '#fff', fontFamily: SJ.font, outline: 'none',
          }}>
            <option value="recent">Recently saved</option>
            <option>Date posted</option>
            <option>Company</option>
          </select>
        </span>
      </div>

      {jobs.map((j, i) => (
        <MiniJobCard key={i} job={j} removeLabel="✕ Remove" removeTone="red"
                     footer={`Saved ${j.savedAgo} ago · Still active`} />
      ))}
    </SeekerPage>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// VIEW HISTORY
// ─────────────────────────────────────────────────────────────────────────
function ViewHistoryScreen() {
  const days = [
    { day: 'Today',
      items: [
        { mark: 'M', title: 'Senior Python Engineer', company: 'Monzo Bank', location: 'London, UK', type: 'Full-time', when: '2 hours ago', count: 1 },
        { mark: 'W', title: 'Staff Product Designer', company: 'Wise', location: 'London · Hybrid', type: 'Full-time', when: '4 hours ago', count: 3 },
        { mark: 'D', title: 'Engineering Manager', company: 'Deliveroo', location: 'London, UK', type: 'Full-time', when: '6 hours ago', count: 1 },
      ],
    },
    { day: 'Yesterday',
      items: [
        { mark: 'C', title: 'Senior Python Engineer', company: 'Cleo AI', location: 'London, UK', type: 'Full-time', when: 'Yesterday', count: 1 },
        { mark: 'O', title: 'Frontend Engineer (React)', company: 'Octopus Energy', location: 'Remote, UK', type: 'Full-time', when: 'Yesterday', count: 2 },
      ],
    },
    { day: 'Earlier this week',
      items: [
        { mark: 'S', title: 'Backend Engineer · Python', company: 'Starling Bank', location: 'London, UK', type: 'Full-time', when: '3 days ago', count: 1 },
        { mark: 'B', title: 'Data Scientist — Pricing', company: 'Bulb', location: 'Remote, UK', type: 'Full-time', when: '4 days ago', count: 1 },
      ],
    },
  ];
  return (
    <SeekerPage activeKey="history" title="View History" subtitle="Jobs you've recently viewed — last 30 days"
                sourceLabel="History source: Analytics API · synced 2 min ago">
      {days.map((d) => (
        <div key={d.day} style={{ marginBottom: 26 }}>
          <h3 style={{
            fontSize: 12, fontWeight: 700, color: SJ.muted,
            textTransform: 'uppercase', letterSpacing: '0.08em', margin: '0 0 10px',
          }}>{d.day}</h3>
          {d.items.map((j, i) => (
            <MiniJobCard key={i} job={j}
                         footer={
                           <>Last viewed <strong>{j.when}</strong>{j.count > 1 && <> · Viewed {j.count} times</>}</>
                         } />
          ))}
        </div>
      ))}
    </SeekerPage>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// EMAIL HISTORY
// ─────────────────────────────────────────────────────────────────────────
function EmailHistoryScreen() {
  const emails = [
    { subject: '3 new Python roles in London this week', status: 'opened', sentAgo: '3 hours',
      jobs: ['Senior Python Engineer at Monzo', 'Backend Engineer at Starling Bank', 'Staff Engineer · Platform at Revolut'], extra: 5 },
    { subject: 'Your daily roundup · 7 new matches', status: 'sent', sentAgo: 'Yesterday',
      jobs: ['Engineering Manager at Deliveroo', 'Senior Python Engineer at Cleo AI', 'Frontend Engineer at Octopus Energy'], extra: 4 },
    { subject: 'Your daily roundup · 4 new matches', status: 'opened', sentAgo: '2 days',
      jobs: ['Data Scientist — Pricing at Bulb', 'Staff Product Designer at Wise'], extra: 2 },
    { subject: 'Your daily roundup · 6 new matches', status: 'sent', sentAgo: '3 days',
      jobs: ['Backend Engineer at GoCardless', 'Staff Engineer at Monzo', 'DevOps Engineer at Cleo AI'], extra: 3 },
    { subject: 'Weekly highlights · 12 picks for you', status: 'failed', sentAgo: '1 week',
      jobs: ['DNS resolution failed during send — retried successfully on the next slot.'], extra: 0, failed: true },
  ];
  const statusMap = {
    sent:   { bg: SJ.greenBg, fg: '#16a34a', label: 'Sent' },
    opened: { bg: SJ.blueRing, fg: '#2563eb', label: 'Opened' },
    failed: { bg: '#fee2e2', fg: SJ.red,    label: 'Failed' },
  };
  return (
    <SeekerPage activeKey="emails" title="Email History" subtitle="Job recommendation emails we've sent you">
      {/* Status banner */}
      <div style={{
        background: 'linear-gradient(180deg, #eff6ff 0%, #f8fbff 100%)',
        border: '1px solid #bfdbfe', borderRadius: 18, padding: 22, marginBottom: 22,
        display: 'flex', justifyContent: 'space-between', gap: 20, alignItems: 'flex-start', flexWrap: 'wrap',
      }}>
        <div>
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '8px 12px', borderRadius: 999, background: SJ.greenBg, color: SJ.green,
            fontSize: 13.5, fontWeight: 700, marginBottom: 12,
          }}>● Job alerts on · Daily</span>
          <p style={{ fontSize: 15, color: SJ.text, margin: 0 }}>
            Your alerts are active. We send personalized recommendations based on your activity and preference signals.
          </p>
        </div>
        <a style={{
          padding: '11px 18px', background: SJ.blue, color: '#fff',
          borderRadius: 10, fontSize: 14, fontWeight: 600, textDecoration: 'none', whiteSpace: 'nowrap',
        }}>Manage job alerts</a>
      </div>

      {emails.map((e, i) => {
        const s = statusMap[e.status];
        return (
          <div key={i} style={{
            background: '#fff', border: `1px solid ${SJ.line}`, borderRadius: 16,
            padding: 22, marginBottom: 14, boxShadow: '0 1px 3px rgba(0,0,0,0.05)',
          }}>
            <div style={{ fontSize: 17, fontWeight: 600, color: SJ.ink2, marginBottom: 10 }}>{e.subject}</div>
            <div style={{ marginBottom: 14 }}>
              <span style={{
                display: 'inline-block', padding: '4px 10px', borderRadius: 8,
                fontSize: 13, fontWeight: 500, background: s.bg, color: s.fg,
              }}>{s.label}</span>
              <span style={{ fontSize: 13, color: SJ.muted, marginLeft: 10 }}>Sent {e.sentAgo} ago</span>
            </div>
            {e.failed ? (
              <p style={{ fontSize: 13.5, color: SJ.muted, margin: 0, fontStyle: 'italic' }}>{e.jobs[0]}</p>
            ) : (
              <>
                <div style={{ fontWeight: 600, fontSize: 13.5, color: SJ.ink2, marginBottom: 8 }}>Jobs included:</div>
                {e.jobs.map((j, k, arr) => (
                  <div key={k} style={{
                    padding: '7px 0',
                    borderBottom: k < arr.length - 1 || e.extra ? `1px solid #f3f4f6` : 'none',
                  }}>
                    <a style={{ color: SJ.blue, textDecoration: 'none', fontWeight: 500, fontSize: 14 }}>{j}</a>
                  </div>
                ))}
                {e.extra > 0 && (
                  <div style={{ fontSize: 13, color: SJ.muted, paddingTop: 8 }}>+ {e.extra} more jobs</div>
                )}
              </>
            )}
          </div>
        );
      })}
    </SeekerPage>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// SETTINGS
// ─────────────────────────────────────────────────────────────────────────
function SettingsScreen() {
  return (
    <SeekerPage activeKey="settings" title="Account Settings" subtitle="Manage your account details and your job alerts in one place.">
      {/* Intro */}
      <div style={{
        background: 'linear-gradient(180deg, #eff6ff 0%, #f8fbff 100%)',
        border: '1px solid #bfdbfe', borderRadius: 18, padding: 22, marginBottom: 22,
      }}>
        <span style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          padding: '8px 12px', borderRadius: 999, background: SJ.greenBg, color: SJ.green,
          fontSize: 13.5, fontWeight: 700, marginBottom: 14,
        }}>● Job alerts on · Daily</span>
        <h3 style={{ fontSize: 22, fontWeight: 700, color: SJ.ink, margin: '0 0 10px' }}>Your job alerts are active</h3>
        <p style={{ color: '#4b5563', margin: 0, fontSize: 14.5 }}>
          We send personalized job recommendation emails based on your activity and profile preferences.
        </p>
        <ul style={{ margin: '16px 0 0', paddingLeft: 20, color: '#4b5563', fontSize: 13.5, lineHeight: 1.8 }}>
          <li>Alerts are delivered to <strong>olena.k@example.com</strong>.</li>
          <li>The frequency selector only applies when email notifications are enabled.</li>
          <li>You can review previously sent emails from your alert history.</li>
        </ul>
        <div style={{ marginTop: 16 }}>
          <a style={{
            display: 'inline-flex', alignItems: 'center', padding: '10px 16px',
            background: SJ.blueSoft, color: SJ.blueDark, border: `1px solid ${SJ.blueRing}`,
            borderRadius: 10, textDecoration: 'none', fontSize: 13.5, fontWeight: 600,
          }}>Open alert email history</a>
        </div>
      </div>

      {/* Profile Information panel */}
      <SettingsPanel title="Profile Information">
        <div style={{ marginBottom: 20, maxWidth: 480 }}>
          <SettingsLabel>Email</SettingsLabel>
          <SettingsInput defaultValue="olena.k@example.com" />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, maxWidth: 480 }}>
          <div>
            <SettingsLabel>First Name</SettingsLabel>
            <SettingsInput defaultValue="Olena" />
          </div>
          <div>
            <SettingsLabel>Last Name</SettingsLabel>
            <SettingsInput defaultValue="Kovalenko" />
          </div>
        </div>
      </SettingsPanel>

      {/* Job alerts panel */}
      <SettingsPanel title="Job Alerts by Email">
        <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 0.8fr', gap: 22, alignItems: 'start' }}>
          <div>
            <div style={{ marginBottom: 16 }}>
              <label style={{
                display: 'flex', alignItems: 'center', gap: 10,
                fontSize: 15, color: '#4b5563', fontWeight: 600, cursor: 'pointer',
              }}>
                <input type="checkbox" defaultChecked style={{ width: 16, height: 16, accentColor: SJ.blue }} />
                Enable job alert emails
              </label>
              <div style={{ fontSize: 13, color: SJ.muted, marginTop: 4, paddingLeft: 26 }}>
                Send personalized recommendations to my inbox based on activity and preference signals.
              </div>
            </div>
            <div style={{ maxWidth: 280 }}>
              <SettingsLabel>Notification Frequency</SettingsLabel>
              <select defaultValue="daily" style={{
                width: '100%', padding: '12px 14px', border: `1px solid ${SJ.line}`,
                borderRadius: 8, fontSize: 14, color: SJ.ink, background: '#fff',
                fontFamily: SJ.font, outline: 'none',
              }}>
                <option value="daily">Daily</option>
                <option value="weekly">Weekly</option>
                <option value="never">Never (turn alerts off)</option>
              </select>
              <div style={{ fontSize: 13, color: SJ.muted, marginTop: 6 }}>
                Choose daily, weekly, or never. Daily is the default for new accounts.
              </div>
            </div>

            <div style={{ marginTop: 22 }}>
              <SettingsLabel>Preferred categories</SettingsLabel>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {['Backend', 'DevOps', 'Data', 'Platform', '+ Add'].map((c) => (
                  <span key={c} style={{
                    padding: '6px 12px', background: c === '+ Add' ? 'transparent' : SJ.blueSoft,
                    color: c === '+ Add' ? SJ.muted : SJ.blueDark,
                    border: `1px ${c === '+ Add' ? 'dashed' : 'solid'} ${c === '+ Add' ? SJ.line : SJ.blueRing}`,
                    borderRadius: 6, fontSize: 12.5, fontWeight: 500, cursor: 'pointer',
                  }}>{c}</span>
                ))}
              </div>
            </div>

            <div style={{ marginTop: 18 }}>
              <SettingsLabel>Preferred locations</SettingsLabel>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {['London', 'Manchester', 'Remote UK', '+ Add'].map((c) => (
                  <span key={c} style={{
                    padding: '6px 12px', background: c === '+ Add' ? 'transparent' : SJ.blueSoft,
                    color: c === '+ Add' ? SJ.muted : SJ.blueDark,
                    border: `1px ${c === '+ Add' ? 'dashed' : 'solid'} ${c === '+ Add' ? SJ.line : SJ.blueRing}`,
                    borderRadius: 6, fontSize: 12.5, fontWeight: 500, cursor: 'pointer',
                  }}>{c}</span>
                ))}
              </div>
            </div>
          </div>

          {/* Status summary */}
          <aside style={{
            background: SJ.page, border: `1px solid ${SJ.line}`, borderRadius: 14, padding: 18,
          }}>
            <div style={{
              fontSize: 12.5, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase',
              color: SJ.muted, marginBottom: 10,
            }}>Current status</div>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '6px 10px', background: SJ.greenBg, color: SJ.green,
              borderRadius: 999, fontSize: 13, fontWeight: 700, marginBottom: 10,
            }}>● Daily alerts enabled</div>
            <p style={{ fontSize: 13.5, color: '#4b5563', margin: '0 0 8px' }}>
              You will receive emails at <strong>olena.k@example.com</strong>.
            </p>
            <p style={{ fontSize: 13.5, color: '#4b5563', margin: 0 }}>
              Last email sent <strong>3 hours ago</strong>.
            </p>
          </aside>
        </div>
      </SettingsPanel>

      {/* Danger zone */}
      <SettingsPanel title="Account">
        <p style={{ fontSize: 14, color: SJ.muted, margin: '0 0 16px' }}>
          Deactivating your account hides your profile and pauses alerts. Deletion is permanent and removes all data after 14 days.
        </p>
        <div style={{ display: 'flex', gap: 10 }}>
          <button style={{
            padding: '11px 18px', background: '#fff', color: SJ.text,
            border: `1px solid ${SJ.line}`, borderRadius: 10,
            fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: SJ.font,
          }}>Deactivate account</button>
          <button style={{
            padding: '11px 18px', background: '#fff', color: SJ.red,
            border: `1px solid ${SJ.redLine}`, borderRadius: 10,
            fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: SJ.font,
          }}>Delete account</button>
        </div>
      </SettingsPanel>

      <div style={{ display: 'flex', gap: 12, marginTop: 8 }}>
        <button style={{
          padding: '12px 24px', background: SJ.blue, color: '#fff',
          border: 'none', borderRadius: 10, fontSize: 15, fontWeight: 600, cursor: 'pointer', fontFamily: SJ.font,
        }}>Save Changes</button>
        <a style={{
          display: 'inline-flex', alignItems: 'center', padding: '12px 24px',
          background: '#f3f4f6', color: '#4b5563', borderRadius: 10,
          textDecoration: 'none', fontSize: 15, fontWeight: 600,
        }}>Cancel</a>
      </div>
    </SeekerPage>
  );
}

function SettingsPanel({ title, children }) {
  return (
    <div style={{
      background: '#fff', border: `1px solid ${SJ.line}`, borderRadius: 16,
      marginBottom: 22, boxShadow: '0 1px 3px rgba(0,0,0,0.05)',
    }}>
      <div style={{
        padding: '14px 22px', borderBottom: `1px solid ${SJ.line}`,
        fontWeight: 600, fontSize: 15.5, color: SJ.ink2,
      }}>{title}</div>
      <div style={{ padding: 22 }}>{children}</div>
    </div>
  );
}

function SettingsLabel({ children }) {
  return (
    <label style={{
      display: 'block', fontSize: 13, fontWeight: 600,
      color: SJ.ink2, marginBottom: 6,
    }}>{children}</label>
  );
}

function SettingsInput({ defaultValue, type = 'text' }) {
  return (
    <input type={type} defaultValue={defaultValue} style={{
      width: '100%', padding: '12px 14px', border: `1px solid ${SJ.line}`,
      borderRadius: 8, fontSize: 14, color: SJ.ink, background: '#fff',
      fontFamily: SJ.font, outline: 'none', boxSizing: 'border-box',
    }} />
  );
}

Object.assign(window, {
  SavedJobsScreen, ViewHistoryScreen, EmailHistoryScreen, SettingsScreen,
});
