// Careers Admin — HR portal to post and manage job openings
// Access at: /careers-admin  |  Password protected

const { useState: useAdminState, useEffect: useAdminEffect, useRef: useAdminRef } = React;

const ADMIN_PASSWORD = 'amg-hr-2024'; // Change this password as needed

// ── Paste your Google Apps Script Web App URL here
const CAREERS_WEBHOOK_URL = 'https://script.google.com/macros/s/AKfycbxnqVfYpcNNFlXw-40W8Z7skRuOMkn81rQlqwD3fNwFUp1H8VJu6FTdycBGGww8hpYl2g/exec';

function genId() {
  return Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
}

// ── Login screen
function AdminLogin({ onLogin }) {
  const [pw, setPw] = useAdminState('');
  const [err, setErr] = useAdminState('');

  const submit = (e) => {
    e.preventDefault();
    if (pw === ADMIN_PASSWORD) { onLogin(); }
    else { setErr('Incorrect password. Please try again.'); setPw(''); }
  };

  return (
    <div className="min-h-screen flex items-center justify-center px-5" style={{background:'var(--bg-base)'}}>
      <div className="w-full max-w-sm">
        <div className="mb-8 text-center">
          <div className="h-14 w-14 rounded-2xl bg-accent/10 border border-accent/20 grid place-items-center text-accent mx-auto mb-5">
            <Icon.Lock size={22}/>
          </div>
          <h1 className="font-display text-[28px] tracking-tightest">HR Admin Portal</h1>
          <p className="mt-2 text-bone-50/45 text-[13px]">Ashok Malhotra Group · Careers</p>
        </div>
        <form onSubmit={submit} className="space-y-4">
          <label className="block">
            <span className="block text-[11px] uppercase tracking-[0.22em] mb-2" style={{color:'var(--ink-fg)',opacity:0.45}}>Admin Password</span>
            <input
              type="password"
              autoFocus
              className="field w-full rounded-xl px-4 py-3.5 text-[15px]"
              style={err ? {borderColor:'rgba(248,113,113,0.7)'} : {}}
              value={pw}
              onChange={e => { setPw(e.target.value); setErr(''); }}
              placeholder="Enter password"
            />
            {err && <span className="block mt-1.5 text-[12px] text-red-400">{err}</span>}
          </label>
          <button
            type="submit"
            className="btn w-full rounded-full bg-bone-50 text-ink-950 px-6 py-4 text-[13px] font-medium tracking-wide hover:bg-accent-soft transition"
          >
            Sign In
          </button>
        </form>
      </div>
    </div>
  );
}

// ── Empty job template
const EMPTY_JOB = {
  title: '',
  department: '',
  location: 'Ludhiana, Punjab',
  type: 'Full-time',
  description: '',
  responsibilities: [''],
  requirements: [''],
  active: true,
};

// ── List editor for responsibilities / requirements
function ListEditor({ label, items, onChange }) {
  const add = () => onChange([...items, '']);
  const remove = (i) => onChange(items.filter((_, idx) => idx !== i));
  const update = (i, val) => onChange(items.map((it, idx) => idx === i ? val : it));

  return (
    <div>
      <span className="block text-[11px] uppercase tracking-[0.22em] mb-2" style={{color:'var(--ink-fg)',opacity:0.45}}>{label}</span>
      <div className="space-y-2">
        {items.map((item, i) => (
          <div key={i} className="flex items-center gap-2">
            <input
              className="field flex-1 rounded-xl px-4 py-2.5 text-[14px]"
              placeholder={`Item ${i + 1}…`}
              value={item}
              onChange={e => update(i, e.target.value)}
            />
            <button
              type="button"
              onClick={() => remove(i)}
              className="h-9 w-9 rounded-lg border border-bone-50/10 grid place-items-center text-bone-50/40 hover:text-red-400 hover:border-red-400/30 transition"
            >
              <Icon.Trash2 size={13}/>
            </button>
          </div>
        ))}
      </div>
      <button
        type="button"
        onClick={add}
        className="mt-2.5 flex items-center gap-2 text-[12px] text-accent hover:text-accent-soft transition"
      >
        <Icon.Plus size={13}/> Add item
      </button>
    </div>
  );
}

// ── Job form (create + edit)
function JobForm({ initial, onSave, onCancel }) {
  const [job, setJob] = useAdminState(initial || EMPTY_JOB);
  const [errors, setErrors] = useAdminState({});

  const set = (key, val) => setJob(p => ({ ...p, [key]: val }));

  const validate = () => {
    const e = {};
    if (!job.title.trim()) e.title = 'Job title is required';
    if (!job.department.trim()) e.department = 'Department is required';
    if (!job.description.trim()) e.description = 'Job description is required';
    return e;
  };

  const handleSave = () => {
    const e = validate();
    if (Object.keys(e).length) { setErrors(e); return; }
    onSave({
      ...job,
      title: job.title.trim(),
      department: job.department.trim(),
      description: job.description.trim(),
      responsibilities: job.responsibilities.filter(r => r.trim()),
      requirements: job.requirements.filter(r => r.trim()),
    });
  };

  return (
    <div className="rounded-3xl border border-bone-50/10 p-6 sm:p-8 space-y-6">
      <div className="grid sm:grid-cols-2 gap-5">
        
        <label className="block">
          <span className="block text-[11px] uppercase tracking-[0.22em] mb-2" style={{color:'var(--ink-fg)',opacity:0.45}}>Job Title *</span>
          <input
            className="field w-full rounded-xl px-4 py-3 text-[14px]"
            style={errors.title ? {borderColor:'rgba(248,113,113,0.7)'} : {}}
            placeholder="e.g. Senior Sales Manager"
            value={job.title}
            onChange={e => set('title', e.target.value)}
          />
          {errors.title && <span className="block mt-1.5 text-[12px] text-red-400">{errors.title}</span>}
        </label>

        <label className="block">
          <span className="block text-[11px] uppercase tracking-[0.22em] mb-2" style={{color:'var(--ink-fg)',opacity:0.45}}>Department *</span>
          <input
            className="field w-full rounded-xl px-4 py-3 text-[14px]"
            style={errors.department ? {borderColor:'rgba(248,113,113,0.7)'} : {}}
            placeholder="e.g. Sales & Marketing"
            value={job.department}
            onChange={e => set('department', e.target.value)}
          />
          {errors.department && <span className="block mt-1.5 text-[12px] text-red-400">{errors.department}</span>}
        </label>

        <label className="block">
          <span className="block text-[11px] uppercase tracking-[0.22em] mb-2" style={{color:'var(--ink-fg)',opacity:0.45}}>Location</span>
          <input
            className="field w-full rounded-xl px-4 py-3 text-[14px]"
            placeholder="Ludhiana, Punjab"
            value={job.location}
            onChange={e => set('location', e.target.value)}
          />
        </label>

        <label className="block">
          <span className="block text-[11px] uppercase tracking-[0.22em] mb-2" style={{color:'var(--ink-fg)',opacity:0.45}}>Employment Type</span>
          <select
            className="field w-full rounded-xl px-4 py-3 text-[14px]"
            value={job.type}
            onChange={e => set('type', e.target.value)}
          >
            <option>Full-time</option>
            <option>Part-time</option>
            <option>Contract</option>
            <option>Internship</option>
            <option>Freelance</option>
          </select>
        </label>

      </div>

      <label className="block">
        <span className="block text-[11px] uppercase tracking-[0.22em] mb-2" style={{color:'var(--ink-fg)',opacity:0.45}}>Job Description *</span>
        <textarea
          rows={4}
          className="field w-full rounded-xl px-4 py-3 text-[14px] resize-none"
          style={errors.description ? {borderColor:'rgba(248,113,113,0.7)'} : {}}
          placeholder="Describe the role, team, and what success looks like…"
          value={job.description}
          onChange={e => set('description', e.target.value)}
        />
        {errors.description && <span className="block mt-1.5 text-[12px] text-red-400">{errors.description}</span>}
      </label>

      <ListEditor
        label="Key Responsibilities"
        items={job.responsibilities}
        onChange={val => set('responsibilities', val)}
      />

      <ListEditor
        label="Requirements & Qualifications"
        items={job.requirements}
        onChange={val => set('requirements', val)}
      />

      {/* Active toggle */}
      <div className="flex items-center justify-between py-4 px-5 rounded-2xl border border-bone-50/10 bg-bone-50/[0.02]">
        <div>
          <p className="text-[14px] text-bone-50/80">Published on careers page</p>
          <p className="text-[12px] text-bone-50/40 mt-0.5">Toggle to show or hide this role publicly</p>
        </div>
        <button
          type="button"
          onClick={() => set('active', !job.active)}
          className={`relative h-7 w-12 rounded-full border transition-colors ${job.active ? 'border-accent bg-accent/20' : 'border-bone-50/20 bg-bone-50/5'}`}
        >
          <span className={`absolute top-0.5 h-6 w-6 rounded-full border transition-all ${job.active ? 'left-5 border-accent bg-accent' : 'left-0.5 border-bone-50/30 bg-bone-50/30'}`}/>
        </button>
      </div>

      <div className="flex gap-3 pt-2">
        <button
          onClick={handleSave}
          className="btn flex-1 rounded-full bg-bone-50 text-ink-950 px-5 py-3.5 text-[13px] font-medium tracking-wide hover:bg-accent-soft inline-flex items-center justify-center gap-2 transition"
        >
          <Icon.Check size={14}/> Save Job Posting
        </button>
        <button
          onClick={onCancel}
          className="btn rounded-full border border-bone-50/20 text-bone-50 px-5 py-3.5 text-[13px] font-medium hover:bg-bone-50/5 transition"
        >
          Cancel
        </button>
      </div>
    </div>
  );
}

// ── Job row in the listing
function AdminJobRow({ job, onEdit, onToggle, onDelete }) {
  const [confirmDelete, setConfirmDelete] = useAdminState(false);

  return (
    <div className={`rounded-2xl border px-5 py-4 flex items-center gap-4 flex-wrap transition ${job.active ? 'border-bone-50/10' : 'border-bone-50/5 opacity-60'}`}
      style={{background:'var(--bg-elev)'}}>
      {/* Status dot */}
      <span className={`h-2 w-2 rounded-full flex-shrink-0 ${job.active ? 'bg-green-400' : 'bg-bone-50/20'}`}/>

      <div className="flex-1 min-w-0">
        <p className="text-[15px] text-bone-50/90 font-medium truncate">{job.title}</p>
        <div className="flex flex-wrap gap-2 mt-1">
          <span className="text-[11px] uppercase tracking-[0.16em] text-accent">{job.department}</span>
          <span className="text-[11px] text-bone-50/35">{job.location} · {job.type}</span>
        </div>
      </div>

      <div className="flex items-center gap-2 flex-shrink-0">
        {/* Toggle active */}
        <button
          onClick={() => onToggle(job.id)}
          title={job.active ? 'Unpublish' : 'Publish'}
          className="h-8 w-8 rounded-lg border border-bone-50/10 grid place-items-center text-bone-50/45 hover:text-accent hover:border-accent/30 transition"
        >
          {job.active ? <Icon.EyeOff size={13}/> : <Icon.Eye size={13}/>}
        </button>
        {/* Edit */}
        <button
          onClick={() => onEdit(job)}
          className="h-8 w-8 rounded-lg border border-bone-50/10 grid place-items-center text-bone-50/45 hover:text-bone-50 hover:border-bone-50/30 transition"
        >
          <Icon.Pencil size={13}/>
        </button>
        {/* Delete */}
        {confirmDelete ? (
          <div className="flex items-center gap-1.5">
            <button onClick={() => onDelete(job.id)} className="h-8 px-3 rounded-lg bg-red-500/20 border border-red-400/30 text-[11px] text-red-400 hover:bg-red-500/30 transition">Delete</button>
            <button onClick={() => setConfirmDelete(false)} className="h-8 px-3 rounded-lg border border-bone-50/10 text-[11px] text-bone-50/40 hover:text-bone-50 transition">Keep</button>
          </div>
        ) : (
          <button
            onClick={() => setConfirmDelete(true)}
            className="h-8 w-8 rounded-lg border border-bone-50/10 grid place-items-center text-bone-50/30 hover:text-red-400 hover:border-red-400/30 transition"
          >
            <Icon.Trash2 size={13}/>
          </button>
        )}
      </div>
    </div>
  );
}

// ── Main Admin page
function CareersAdminPage({ setPage }) {
  const [authed, setAuthed] = useAdminState(() => {
    try { return sessionStorage.getItem('amg-hr-authed') === 'yes'; } catch(e) { return false; }
  });
  const [jobs, setJobs] = useAdminState([]);
  const [loading, setLoading] = useAdminState(true);
  const [mode, setMode] = useAdminState('list'); // list | create | edit
  const [editingJob, setEditingJob] = useAdminState(null);
  const [saved, setSaved] = useAdminState(false);

  // Fetch jobs from Google Sheets on load
  useAdminEffect(() => {
    if (authed) {
      fetch(CAREERS_WEBHOOK_URL)
        .then(res => res.json())
        .then(data => { setJobs(data); setLoading(false); })
        .catch(err => { console.error('Failed to load jobs', err); setLoading(false); });
    }
  }, [authed]);

  const login = () => {
    try { sessionStorage.setItem('amg-hr-authed', 'yes'); } catch(e) {}
    setAuthed(true);
  };

  const logout = () => {
    try { sessionStorage.removeItem('amg-hr-authed'); } catch(e) {}
    setAuthed(false);
  };

  const persist = (updated) => {
    // 1. Optimistic UI update
    setJobs(updated);
    
    // 2. Save to Google Sheets
    fetch(CAREERS_WEBHOOK_URL, {
      method: 'POST',
      mode: 'no-cors',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action: 'save_jobs', jobs: updated })
    }).catch(console.error);

    setSaved(true);
    setTimeout(() => setSaved(false), 2500);
  };

  const handleCreate = (job) => {
    persist([{ ...job, id: genId(), createdAt: new Date().toISOString() }, ...jobs]);
    setMode('list');
  };

  const handleEdit = (job) => {
    const updated = jobs.map(j => j.id === job.id ? { ...job } : j);
    persist(updated);
    setMode('list');
    setEditingJob(null);
  };

  const toggleActive = (id) => {
    persist(jobs.map(j => j.id === id ? { ...j, active: !j.active } : j));
  };

  const deleteJob = (id) => {
    persist(jobs.filter(j => j.id !== id));
  };

  if (!authed) return <AdminLogin onLogin={login}/>;

  return (
    <main className="min-h-screen pt-28 pb-20" style={{background:'var(--bg-base)'}}>
      <div className="mx-auto max-w-[1600px] px-5 sm:px-8">

        {/* Header */}
        <div className="flex items-start justify-between gap-4 mb-10 flex-wrap">
          <div>
            <div className="flex items-center gap-2 mb-2">
              <div className="h-8 w-8 rounded-xl bg-accent/10 grid place-items-center text-accent">
                <Icon.Briefcase size={15}/>
              </div>
              <span className="text-[11px] uppercase tracking-[0.22em] text-accent">HR Admin Panel</span>
            </div>
            <h1 className="font-display text-[32px] sm:text-[44px] tracking-tightest leading-[0.98]">
              Careers<br/><span className="italic text-accent-soft">Management</span>
            </h1>
          </div>
          <div className="flex items-center gap-3">
            {saved && (
              <span className="flex items-center gap-1.5 text-[12px] text-green-400">
                <Icon.Check size={13}/> Saved
              </span>
            )}
            <button
              onClick={() => setPage('careers')}
              className="btn rounded-full border border-bone-50/15 text-bone-50/60 px-4 py-2.5 text-[12px] hover:text-bone-50 hover:border-bone-50/30 inline-flex items-center gap-2 transition"
            >
              <Icon.ExternalLink size={13}/> Preview Page
            </button>
            <button
              onClick={logout}
              className="btn rounded-full border border-bone-50/15 text-bone-50/50 px-4 py-2.5 text-[12px] hover:text-red-400 hover:border-red-400/30 transition"
            >
              Sign out
            </button>
          </div>
        </div>

        {/* Stats bar */}
        <div className="grid grid-cols-3 gap-3 mb-8">
          {[
            { label: 'Total Postings', value: jobs.length },
            { label: 'Published', value: jobs.filter(j => j.active).length },
            { label: 'Drafts', value: jobs.filter(j => !j.active).length },
          ].map(s => (
            <div key={s.label} className="rounded-2xl border border-bone-50/10 px-4 py-4 text-center" style={{background:'var(--bg-elev)'}}>
              <div className="font-display text-[28px] text-accent-soft">{s.value}</div>
              <div className="text-[11px] uppercase tracking-[0.18em] mt-1" style={{color:'var(--ink-fg)',opacity:0.4}}>{s.label}</div>
            </div>
          ))}
        </div>

        {/* Create / Edit form */}
        {mode === 'create' && (
          <div className="mb-8">
            <div className="flex items-center gap-3 mb-5">
              <h2 className="font-display text-[22px]">New Job Posting</h2>
            </div>
            <JobForm onSave={handleCreate} onCancel={() => setMode('list')}/>
          </div>
        )}

        {mode === 'edit' && editingJob && (
          <div className="mb-8">
            <div className="flex items-center gap-3 mb-5">
              <h2 className="font-display text-[22px]">Edit: {editingJob.title}</h2>
            </div>
            <JobForm
              initial={editingJob}
              onSave={handleEdit}
              onCancel={() => { setMode('list'); setEditingJob(null); }}
            />
          </div>
        )}

        {/* Job list */}
        {mode === 'list' && (
          <>
            <div className="flex items-center justify-between gap-4 mb-5 flex-wrap">
              <h2 className="font-display text-[20px]">All Postings</h2>
              <button
                onClick={() => setMode('create')}
                className="btn rounded-full bg-bone-50 text-ink-950 px-5 py-3 text-[12px] font-medium tracking-wide hover:bg-accent-soft inline-flex items-center gap-2 transition"
              >
                <Icon.Plus size={14}/> New Opening
              </button>
            </div>

            {loading ? (
              <div className="rounded-3xl border border-bone-50/10 py-16 text-center">
                <span className="inline-block h-6 w-6 border-2 border-bone-50/30 border-t-accent rounded-full animate-spin mb-3"/>
                <p className="text-bone-50/40 text-[14px]">Loading jobs from database...</p>
              </div>
            ) : jobs.length === 0 ? (
              <div className="rounded-3xl border border-bone-50/10 border-dashed py-16 text-center">
                <Icon.Briefcase size={28} className="mx-auto text-bone-50/20 mb-3"/>
                <p className="text-bone-50/40 text-[14px]">No job postings yet.</p>
                <button
                  onClick={() => setMode('create')}
                  className="mt-5 btn rounded-full border border-bone-50/15 text-bone-50/60 px-5 py-2.5 text-[12px] hover:text-bone-50 hover:border-bone-50/30 inline-flex items-center gap-2 transition"
                >
                  <Icon.Plus size={13}/> Create your first posting
                </button>
              </div>
            ) : (
              <div className="space-y-2.5">
                {jobs.map(job => (
                  <AdminJobRow
                    key={job.id}
                    job={job}
                    onEdit={(j) => { setEditingJob(j); setMode('edit'); }}
                    onToggle={toggleActive}
                    onDelete={deleteJob}
                  />
                ))}
              </div>
            )}

            {/* Help note */}
            <div className="mt-10 rounded-2xl border border-bone-50/8 bg-bone-50/[0.02] px-5 py-4 flex items-start gap-3">
              <Icon.Info size={14} className="text-accent flex-shrink-0 mt-0.5"/>
              <div className="text-[12px] text-bone-50/45 leading-relaxed">
                <strong className="text-bone-50/60">How it works:</strong> Job postings are stored securely in your Google Sheet's <strong>Jobs</strong> tab. Any changes made here are instantly saved to the database and will reflect on the public <strong className="text-bone-50/60">Careers</strong> page immediately.
              </div>
            </div>
          </>
        )}

      </div>
    </main>
  );
}

window.CareersAdminPage = CareersAdminPage;
