// src/app/(public)/resume/builder/page.tsx
'use client'

import { useState, useEffect, useCallback } from 'react'
import { useSession } from 'next-auth/react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { Textarea } from '@/components/ui/Textarea'
import { Select } from '@/components/ui/Select'
import { Spinner } from '@/components/ui/Spinner'
import { ResumePreview } from '@/components/resume/ResumePreview'
import type { ResumeData, ResumeExperienceData, ResumeEducationData, ResumeSkillData, ResumeProjectData } from '@/types'

const TEMPLATES = [
  { id: 'clean-professional', name: 'Clean Professional', color: '#2b2ca8' },
  { id: 'modern-sidebar', name: 'Modern Sidebar', color: '#5563f5' },
  { id: 'compact-ats', name: 'Compact ATS', color: '#27272a' },
  { id: 'creative-accent', name: 'Creative Accent', color: '#e11d48' },
  { id: 'executive-classic', name: 'Executive Classic', color: '#1a1a50' },
  { id: 'graduate-simple', name: 'Graduate Simple', color: '#059669' },
  { id: 'motif-custom', name: 'Motif Custom', color: '#3b82f6' },
  { id: 'elegant-minimalist', name: 'Elegant Minimalist', color: '#0d9488' },
  { id: 'creative-geometric', name: 'Creative Geometric', color: '#7c3aed' },
]

const SKILL_LEVELS = [
  { value: '', label: 'No level' },
  { value: 'Beginner', label: 'Beginner' },
  { value: 'Intermediate', label: 'Intermediate' },
  { value: 'Advanced', label: 'Advanced' },
  { value: 'Expert', label: 'Expert' },
]

const ACCENT_PRESETS = ['#5563f5', '#2b2ca8', '#e11d48', '#059669', '#d97706', '#1a1a50', '#27272a', '#0891b2']

const GOOGLE_FONTS = [
  { id: 'sans', family: 'Montserrat', name: 'Montserrat (Sans)' },
  { id: 'sans2', family: 'Inter', name: 'Inter (Sans)' },
  { id: 'sans3', family: 'Space Grotesk', name: 'Space Grotesk (Creative)' },
  { id: 'serif', family: 'Lora', name: 'Lora (Serif)' },
  { id: 'serif2', family: 'Zilla Slab', name: 'Zilla Slab (Serif)' },
  { id: 'serif3', family: 'EB Garamond', name: 'EB Garamond (Classic Serif)' },
  { id: 'serif4', family: 'Aleo', name: 'Aleo (Serif)' },
  { id: 'serif5', family: 'PT Serif', name: 'PT Serif (Serif)' },
  { id: 'mono', family: 'Courier Prime', name: 'Courier Prime (Mono)' },
]

const defaultDesignSettings = () => JSON.stringify({
  fontSize: '10pt',
  lineHeight: '1.4',
  marginLR: '18mm',
  marginTB: '16mm',
  entrySpacing: '14px',
  columns: 'one',
  headerPosition: 'top',
  columnWidthLeft: 40,
  columnWidthRight: 60,
  titleSubtitleSize: 'M',
  subtitleStyle: 'Bold',
  subtitlePlacement: 'nextLine',
  indentBody: false,
  listStyle: 'bullet',
  footerPageNumbers: false,
  footerEmail: false,
  footerName: false,
  fontType: 'sans',
  fontFamily: 'Montserrat',
  linkUnderline: true,
  linkBlueColor: true,
  linkIcon: true,
  detailsArrangement: 'bullet',
  iconStyle: 'none',
  nameSize: 'l',
  nameBold: true,
  photoStyle: 'circle',
  photoSize: 90,
  photoBorder: true,
  photoAlignment: 'left'
})

const emptyResume = (): ResumeData => ({
  templateId: 'motif-custom',
  title: 'My Resume',
  fullName: '',
  email: '',
  phone: '',
  location: '',
  summary: '',
  accentColor: '#5563f5',
  professionalTitle: '',
  photoUrl: '',
  designSettings: defaultDesignSettings(),
  experiences: [],
  education: [],
  skills: [],
  projects: [],
})

type Tab = 'personal' | 'experience' | 'education' | 'skills' | 'projects' | 'design'

export default function ResumeBuilderPage() {
  const { data: session, status } = useSession()
  const router = useRouter()
  const [resume, setResume] = useState<ResumeData>(emptyResume())
  const [savedId, setSavedId] = useState<string | null>(null)
  const [savedResumes, setSavedResumes] = useState<(ResumeData & { id: string; updatedAt: string })[]>([])
  const [tab, setTab] = useState<Tab>('design')
  const [saving, setSaving] = useState(false)
  const [saveMessage, setSaveMessage] = useState('')
  const [loading, setLoading] = useState(false)
  const [showSavedList, setShowSavedList] = useState(false)
  const [copiedLink, setCopiedLink] = useState(false)

  // Current parsed design settings
  const getDesignSetting = (key: string, fallback: any) => {
    try {
      const parsed = JSON.parse(resume.designSettings || '{}')
      return parsed[key] !== undefined ? parsed[key] : fallback
    } catch {
      return fallback
    }
  }

  const updateDesignSetting = (key: string, value: any) => {
    try {
      const parsed = JSON.parse(resume.designSettings || '{}')
      parsed[key] = value
      setResume(r => ({ ...r, designSettings: JSON.stringify(parsed) }))
    } catch {
      const parsed = JSON.parse(defaultDesignSettings())
      parsed[key] = value
      setResume(r => ({ ...r, designSettings: JSON.stringify(parsed) }))
    }
  }

  const fetchSaved = useCallback(async () => {
    if (!session) return
    const res = await fetch('/api/resume')
    const data = await res.json()
    setSavedResumes(data.resumes ?? [])
  }, [session])

  useEffect(() => {
    if (session) fetchSaved()
  }, [session, fetchSaved])

  if (status === 'loading') return <div className="flex justify-center py-20"><Spinner size="lg" /></div>
  if (!session) {
    return (
      <div className="max-w-xl mx-auto px-4 py-20 text-center">
        <h1 className="page-title mb-4">Resume Builder</h1>
        <p className="text-neutral-500 mb-6">Sign in to build and save your resume.</p>
        <Button onClick={() => router.push('/login?callbackUrl=/resume/builder')}>Sign In to Continue</Button>
      </div>
    )
  }

  function update(field: keyof ResumeData, value: unknown) {
    setResume((r) => ({ ...r, [field]: value }))
  }

  const handlePhotoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return
    const reader = new FileReader()
    reader.onloadend = () => {
      update('photoUrl', reader.result as string)
    }
    reader.readAsDataURL(file)
  }

  // ── Experience helpers ─────────────────────────────────────────────────
  function addExp() {
    const newExp: ResumeExperienceData = { jobTitle: '', company: '', startDate: '', current: false, order: resume.experiences.length }
    setResume((r) => ({ ...r, experiences: [...r.experiences, newExp] }))
  }
  function updateExp(idx: number, field: keyof ResumeExperienceData, value: unknown) {
    setResume((r) => {
      const exps = [...r.experiences]
      exps[idx] = { ...exps[idx], [field]: value }
      return { ...r, experiences: exps }
    })
  }
  function removeExp(idx: number) {
    setResume((r) => ({ ...r, experiences: r.experiences.filter((_, i) => i !== idx) }))
  }

  // ── Education helpers ──────────────────────────────────────────────────
  function addEdu() {
    const newEdu: ResumeEducationData = { degree: '', institution: '', startDate: '', order: resume.education.length }
    setResume((r) => ({ ...r, education: [...r.education, newEdu] }))
  }
  function updateEdu(idx: number, field: keyof ResumeEducationData, value: unknown) {
    setResume((r) => {
      const edus = [...r.education]
      edus[idx] = { ...edus[idx], [field]: value }
      return { ...r, education: edus }
    })
  }
  function removeEdu(idx: number) {
    setResume((r) => ({ ...r, education: r.education.filter((_, i) => i !== idx) }))
  }

  // ── Skill helpers ──────────────────────────────────────────────────────
  function addSkill() {
    const newSkill: ResumeSkillData = { name: '', order: resume.skills.length }
    setResume((r) => ({ ...r, skills: [...r.skills, newSkill] }))
  }
  function updateSkill(idx: number, field: keyof ResumeSkillData, value: unknown) {
    setResume((r) => {
      const skills = [...r.skills]
      skills[idx] = { ...skills[idx], [field]: value }
      return { ...r, skills }
    })
  }
  function removeSkill(idx: number) {
    setResume((r) => ({ ...r, skills: r.skills.filter((_, i) => i !== idx) }))
  }

  // ── Project helpers ────────────────────────────────────────────────────
  function addProject() {
    const newProj: ResumeProjectData = { name: '', order: resume.projects.length }
    setResume((r) => ({ ...r, projects: [...r.projects, newProj] }))
  }
  function updateProject(idx: number, field: keyof ResumeProjectData, value: unknown) {
    setResume((r) => {
      const projects = [...r.projects]
      projects[idx] = { ...projects[idx], [field]: value }
      return { ...r, projects }
    })
  }
  function removeProject(idx: number) {
    setResume((r) => ({ ...r, projects: r.projects.filter((_, i) => i !== idx) }))
  }

  // ── Save ───────────────────────────────────────────────────────────────
  async function handleSave() {
    setSaving(true)
    setSaveMessage('')
    try {
      const url = savedId ? `/api/resume/${savedId}` : '/api/resume'
      const method = savedId ? 'PUT' : 'POST'
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(resume),
      })
      const data = await res.json()
      if (res.ok) {
        setSavedId(data.resume.id)
        setSaveMessage('Saved!')
        await fetchSaved()
      } else {
        setSaveMessage(data.error ?? 'Save failed')
      }
    } catch {
      setSaveMessage('Save failed')
    } finally {
      setSaving(false)
      setTimeout(() => setSaveMessage(''), 3000)
    }
  }

  function loadResume(r: ResumeData & { id: string }) {
    setSavedId(r.id)
    setResume({
      ...r,
      designSettings: r.designSettings || defaultDesignSettings()
    })
    setShowSavedList(false)
  }

  async function duplicateResume() {
    const copy = { ...resume, title: resume.title + ' (copy)', id: undefined }
    const res = await fetch('/api/resume', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(copy),
    })
    if (res.ok) {
      const data = await res.json()
      setSavedId(data.resume.id)
      await fetchSaved()
      setSaveMessage('Duplicated!')
    }
  }

  async function deleteResume() {
    if (!savedId || !confirm('Delete this resume?')) return
    await fetch(`/api/resume/${savedId}`, { method: 'DELETE' })
    setResume(emptyResume())
    setSavedId(null)
    await fetchSaved()
  }

  function handlePrint() {
    window.print()
  }

  function handleEmail() {
    const subject = encodeURIComponent(`My Resume — ${resume.fullName}`)
    const body = encodeURIComponent(
      `Hi,\n\nPlease find my resume attached.\n\nTo view my interactive design layout, open this private link:\n${window.location.origin}/resume/preview/${savedId || ''}\n\nBest regards,\n${resume.fullName}`
    )
    window.location.href = `mailto:?subject=${subject}&body=${body}`
  }

  const copyShareLink = () => {
    if (!savedId) return
    const url = `${window.location.origin}/resume/preview/${savedId}`
    navigator.clipboard.writeText(url)
    setCopiedLink(true)
    setTimeout(() => setCopiedLink(false), 2000)
  }

  const tabs: { id: Tab; label: string }[] = [
    { id: 'design', label: 'Resume Template' },
    { id: 'personal', label: 'Personal' },
    { id: 'experience', label: 'Experience' },
    { id: 'education', label: 'Education' },
    { id: 'skills', label: 'Skills' },
    { id: 'projects', label: 'Projects' },
  ]

  return (
    <div className="min-h-screen bg-neutral-50">
      {/* Top toolbar */}
      <div className="no-print bg-white border-b border-neutral-200 sticky top-0 z-30 shadow-sm">
        <div className="max-w-screen-2xl mx-auto px-4 py-3 flex items-center gap-3 flex-wrap">
          <Input
            id="resume-title"
            value={resume.title}
            onChange={(e) => update('title', e.target.value)}
            className="w-48 text-sm font-semibold"
            placeholder="Resume title"
          />
          <div className="flex items-center gap-2 flex-wrap ml-auto">
            {savedResumes.length > 0 && (
              <Button variant="ghost" size="sm" onClick={() => setShowSavedList((v) => !v)}>
                My Resumes ({savedResumes.length})
              </Button>
            )}
            {savedId && (
              <>
                <Button variant="ghost" size="sm" onClick={duplicateResume}>Duplicate</Button>
                <Button variant="danger" size="sm" onClick={deleteResume}>Delete</Button>
              </>
            )}
            <Button variant="secondary" size="sm" onClick={() => setResume(emptyResume())}>New</Button>
            <Button variant="secondary" size="sm" onClick={handleEmail}>✉ Email</Button>
            <Button variant="secondary" size="sm" onClick={handlePrint}>🖨 Download PDF</Button>
            <Button size="sm" loading={saving} onClick={handleSave}>
              {savedId ? 'Update' : 'Save'}
            </Button>
            {saveMessage && <span className="text-xs text-emerald-600 font-medium">{saveMessage}</span>}
          </div>
        </div>

        {/* Saved resumes dropdown */}
        {showSavedList && (
          <div className="border-t border-neutral-100 bg-white max-h-48 overflow-y-auto shadow-md">
            {savedResumes.map((r) => (
              <button
                key={r.id}
                onClick={() => loadResume(r)}
                className={`w-full text-left px-4 py-2.5 text-sm hover:bg-neutral-50 flex items-center justify-between ${r.id === savedId ? 'bg-brand-50 text-brand-700' : 'text-neutral-700'}`}
              >
                <span className="font-medium">{r.title}</span>
                <span className="text-xs text-neutral-400">{new Date(r.updatedAt).toLocaleDateString()}</span>
              </button>
            ))}
          </div>
        )}
      </div>

      <div className="max-w-screen-2xl mx-auto flex h-[calc(100vh-57px)]">
        {/* Left: Editor */}
        <div className="no-print w-full lg:w-[480px] xl:w-[540px] shrink-0 bg-white border-r border-neutral-200 flex overflow-hidden shadow-inner">
          {/* Tab nav */}
          <div className="w-44 shrink-0 bg-neutral-50 border-r border-neutral-100 flex flex-col p-3 gap-1.5 pt-6 sticky top-0">
            {tabs.map((t) => (
              <button
                key={t.id}
                onClick={() => setTab(t.id)}
                className={`w-full px-3 py-2.5 text-left text-xs font-bold transition-all border-r-4 ${
                  tab === t.id
                    ? 'border-brand-600 text-brand-700 bg-white shadow-sm'
                    : 'border-transparent text-neutral-500 hover:text-neutral-800 hover:bg-neutral-100'
                }`}
                style={{ fontFamily: 'var(--font-heading)' }}
              >
                {t.label}
              </button>
            ))}
          </div>

          <div className="flex-1 overflow-y-auto scrollbar-thin p-6 space-y-6">
            {/* Personal */}
            {tab === 'personal' && (
              <div className="space-y-4">
                <Input label="Full name" id="builder-name" value={resume.fullName} onChange={(e) => update('fullName', e.target.value)} placeholder="Amara Nkosi" />
                <Input
                  label="Professional title"
                  id="builder-professional-title"
                  value={resume.professionalTitle || ''}
                  onChange={(e) => update('professionalTitle', e.target.value)}
                  placeholder="Frontend Developer / Senior UX Designer"
                />
                
                {/* Photo Upload Section */}
                <div className="border border-neutral-200 p-4 rounded-xl space-y-3 bg-neutral-50">
                  <span className="block text-xs font-bold text-neutral-700 uppercase tracking-wider">Profile Photo 📸</span>
                  <div className="flex items-center gap-4">
                    {resume.photoUrl ? (
                      <div className="relative">
                        <img src={resume.photoUrl} alt="Preview" className="h-16 w-16 object-cover rounded-full border-2 border-brand-500 shadow-sm" />
                        <button
                          onClick={() => update('photoUrl', '')}
                          className="absolute -top-1 -right-1 bg-red-500 text-white rounded-full p-1 text-[8px] leading-none"
                          title="Remove Photo"
                        >
                          ✕
                        </button>
                      </div>
                    ) : (
                      <div className="h-16 w-16 rounded-full bg-neutral-200 flex items-center justify-center text-xs text-neutral-500 border border-dashed border-neutral-400">
                        No Photo
                      </div>
                    )}
                    <div className="flex-1">
                      <input
                        type="file"
                        accept="image/*"
                        onChange={handlePhotoUpload}
                        className="text-xs text-neutral-500 file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border-0 file:text-xs file:font-semibold file:bg-brand-50 file:text-brand-700 hover:file:bg-brand-100 cursor-pointer"
                      />
                      <span className="block text-[10px] text-neutral-400 mt-1">PNG, JPG up to 1MB. Automatically converted to localized secure offline string.</span>
                    </div>
                  </div>
                </div>

                <Input label="Email" id="builder-email" type="email" value={resume.email} onChange={(e) => update('email', e.target.value)} placeholder="amara@example.com" />
                <div className="grid grid-cols-2 gap-3">
                  <Input label="Phone" id="builder-phone" value={resume.phone ?? ''} onChange={(e) => update('phone', e.target.value)} placeholder="+27 82 555 0101" />
                  <Input label="Location" id="builder-location" value={resume.location ?? ''} onChange={(e) => update('location', e.target.value)} placeholder="Cape Town, ZA" />
                </div>
                <Textarea label="Professional summary" id="builder-summary" value={resume.summary ?? ''} onChange={(e) => update('summary', e.target.value)} placeholder="A brief professional summary..." className="min-h-[100px]" maxLength={800} />
              </div>
            )}

            {/* Experience */}
            {tab === 'experience' && (
              <div className="space-y-4">
                {resume.experiences.map((exp, idx) => (
                  <div key={idx} className="card p-4 space-y-3 border border-neutral-200 rounded-xl bg-white shadow-sm">
                    <div className="flex items-center justify-between">
                      <p className="text-sm font-bold text-neutral-700" style={{ fontFamily: 'Space Grotesk, sans-serif' }}>Experience {idx + 1}</p>
                      <Button variant="ghost" size="sm" onClick={() => removeExp(idx)} className="text-red-500 hover:bg-red-50">Remove</Button>
                    </div>
                    <Input label="Job title" id={`exp-title-${idx}`} value={exp.jobTitle} onChange={(e) => updateExp(idx, 'jobTitle', e.target.value)} placeholder="Frontend Developer" />
                    <Input label="Company" id={`exp-company-${idx}`} value={exp.company} onChange={(e) => updateExp(idx, 'company', e.target.value)} placeholder="TechCo" />
                    <Input label="Location" id={`exp-loc-${idx}`} value={exp.location ?? ''} onChange={(e) => updateExp(idx, 'location', e.target.value)} placeholder="Cape Town" />
                    <div className="grid grid-cols-2 gap-3">
                      <Input label="Start date" id={`exp-start-${idx}`} value={exp.startDate} onChange={(e) => updateExp(idx, 'startDate', e.target.value)} placeholder="2022-03" />
                      <Input label="End date" id={`exp-end-${idx}`} value={exp.endDate ?? ''} onChange={(e) => updateExp(idx, 'endDate', e.target.value)} placeholder="2024-01" disabled={exp.current} />
                    </div>
                    <label className="flex items-center gap-2 text-sm text-neutral-700 cursor-pointer">
                      <input type="checkbox" checked={exp.current} onChange={(e) => updateExp(idx, 'current', e.target.checked)} className="rounded" />
                      Currently working here
                    </label>
                    <Textarea label="Description" id={`exp-desc-${idx}`} value={exp.description ?? ''} onChange={(e) => updateExp(idx, 'description', e.target.value)} placeholder="Key responsibilities and achievements..." className="min-h-[80px]" />
                  </div>
                ))}
                <Button variant="secondary" onClick={addExp} className="w-full">+ Add Experience</Button>
              </div>
            )}

            {/* Education */}
            {tab === 'education' && (
              <div className="space-y-4">
                {resume.education.map((edu, idx) => (
                  <div key={idx} className="card p-4 space-y-3 border border-neutral-200 rounded-xl bg-white shadow-sm">
                    <div className="flex items-center justify-between">
                      <p className="text-sm font-bold text-neutral-700" style={{ fontFamily: 'Space Grotesk, sans-serif' }}>Education {idx + 1}</p>
                      <Button variant="ghost" size="sm" onClick={() => removeEdu(idx)} className="text-red-500 hover:bg-red-50">Remove</Button>
                    </div>
                    <Input label="Degree / qualification" id={`edu-degree-${idx}`} value={edu.degree} onChange={(e) => updateEdu(idx, 'degree', e.target.value)} placeholder="BSc Computer Science" />
                    <Input label="Institution" id={`edu-inst-${idx}`} value={edu.institution} onChange={(e) => updateEdu(idx, 'institution', e.target.value)} placeholder="University of Cape Town" />
                    <Input label="Location" id={`edu-loc-${idx}`} value={edu.location ?? ''} onChange={(e) => updateEdu(idx, 'location', e.target.value)} />
                    <div className="grid grid-cols-2 gap-3">
                      <Input label="Start date" id={`edu-start-${idx}`} value={edu.startDate} onChange={(e) => updateEdu(idx, 'startDate', e.target.value)} placeholder="2019-02" />
                      <Input label="End date" id={`edu-end-${idx}`} value={edu.endDate ?? ''} onChange={(e) => updateEdu(idx, 'endDate', e.target.value)} placeholder="2023-11" />
                    </div>
                    <Textarea label="Description" id={`edu-desc-${idx}`} value={edu.description ?? ''} onChange={(e) => updateEdu(idx, 'description', e.target.value)} className="min-h-[60px]" />
                  </div>
                ))}
                <Button variant="secondary" onClick={addEdu} className="w-full">+ Add Education</Button>
              </div>
            )}

            {/* Skills */}
            {tab === 'skills' && (
              <div className="space-y-4">
                {resume.skills.map((skill, idx) => (
                  <div key={idx} className="flex items-end gap-2 bg-white p-2 rounded-lg border border-neutral-100 shadow-sm">
                    <div className="flex-1">
                      <Input label={idx === 0 ? 'Skill name' : undefined} id={`skill-name-${idx}`} value={skill.name} onChange={(e) => updateSkill(idx, 'name', e.target.value)} placeholder="React" />
                    </div>
                    <div className="w-36">
                      <Select
                        label={idx === 0 ? 'Level' : undefined}
                        id={`skill-level-${idx}`}
                        value={skill.level ?? ''}
                        onChange={(e) => updateSkill(idx, 'level', e.target.value)}
                        options={SKILL_LEVELS}
                      />
                    </div>
                    <Button variant="ghost" size="sm" onClick={() => removeSkill(idx)} className="text-red-500 mb-0.5 shrink-0">✕</Button>
                  </div>
                ))}
                <Button variant="secondary" onClick={addSkill} className="w-full">+ Add Skill</Button>
              </div>
            )}

            {/* Projects */}
            {tab === 'projects' && (
              <div className="space-y-4">
                {resume.projects.map((proj, idx) => (
                  <div key={idx} className="card p-4 space-y-3 border border-neutral-200 rounded-xl bg-white shadow-sm">
                    <div className="flex items-center justify-between">
                      <p className="text-sm font-bold text-neutral-700" style={{ fontFamily: 'Space Grotesk, sans-serif' }}>Project {idx + 1}</p>
                      <Button variant="ghost" size="sm" onClick={() => removeProject(idx)} className="text-red-500 hover:bg-red-50">Remove</Button>
                    </div>
                    <Input label="Project name" id={`proj-name-${idx}`} value={proj.name} onChange={(e) => updateProject(idx, 'name', e.target.value)} placeholder="StudyBuddy App" />
                    <Input label="URL (optional)" id={`proj-url-${idx}`} type="url" value={proj.url ?? ''} onChange={(e) => updateProject(idx, 'url', e.target.value)} placeholder="https://github.com/..." />
                    <Textarea label="Description" id={`proj-desc-${idx}`} value={proj.description ?? ''} onChange={(e) => updateProject(idx, 'description', e.target.value)} className="min-h-[70px]" />
                  </div>
                ))}
                <Button variant="secondary" onClick={addProject} className="w-full">+ Add Project</Button>
              </div>
            )}

            {/* Design */}
            {tab === 'design' && (
              <div className="space-y-6 pb-12">
                {/* 1. Template selection */}
                <div className="space-y-3">
                  <p className="text-xs font-bold text-neutral-700 uppercase tracking-wider" style={{ fontFamily: 'Space Grotesk, sans-serif' }}>Template Layout</p>
                  <div className="grid grid-cols-2 gap-2">
                    {TEMPLATES.map((tmpl) => (
                      <button
                        key={tmpl.id}
                        onClick={() => update('templateId', tmpl.id)}
                        className={`p-3 rounded-xl border-2 text-left transition-all ${
                          resume.templateId === tmpl.id
                            ? 'border-brand-600 bg-brand-50'
                            : 'border-neutral-200 bg-white hover:border-neutral-300'
                        }`}
                      >
                        <div className="flex items-center gap-2 mb-1">
                          <span className="h-4 w-4 rounded" style={{ background: tmpl.color }} />
                          <span className="text-xs font-bold text-neutral-800" style={{ fontFamily: 'Space Grotesk, sans-serif' }}>
                            {tmpl.name}
                          </span>
                        </div>
                      </button>
                    ))}
                  </div>
                </div>

                {/* 2. Color selection */}
                <div className="space-y-3">
                  <p className="text-xs font-bold text-neutral-700 uppercase tracking-wider" style={{ fontFamily: 'Space Grotesk, sans-serif' }}>Accent color</p>
                  <div className="flex flex-wrap gap-2 mb-3">
                    {ACCENT_PRESETS.map((color) => (
                      <button
                        key={color}
                        onClick={() => update('accentColor', color)}
                        className={`h-8 w-8 rounded-full border-2 transition-all ${resume.accentColor === color ? 'border-neutral-900 scale-110' : 'border-neutral-200'}`}
                        style={{ background: color }}
                        title={color}
                      />
                    ))}
                  </div>
                  <Input
                    label="Custom hex color"
                    id="accent-custom"
                    type="color"
                    value={resume.accentColor}
                    onChange={(e) => update('accentColor', e.target.value)}
                    className="h-10 p-1 cursor-pointer"
                  />
                </div>

                {/* Motif Customizable Options Panel (Applies universally to all templates) */}
                <div className="border-t border-neutral-200 pt-6 space-y-6">
                  <div className="bg-brand-50/50 p-4 rounded-xl border border-brand-100">
                    <h3 className="text-sm font-bold text-brand-800 flex items-center gap-1.5" style={{ fontFamily: 'Space Grotesk, sans-serif' }}>
                      <span>⚙️ Motif Custom Settings</span>
                      <span className="text-[10px] bg-emerald-100 text-emerald-800 px-2 py-0.5 rounded">Applies to all templates</span>
                    </h3>
                    <p className="text-[11px] text-neutral-500 mt-1">Configure columns, spacing, header positioning, separators, and advanced typographies.</p>
                  </div>

                  {/* Columns Layout */}
                  <div className="space-y-3">
                    <label className="text-xs font-bold text-neutral-700 uppercase tracking-wider block">Columns Layout</label>
                    <div className="grid grid-cols-2 gap-2">
                      <button
                        onClick={() => updateDesignSetting('columns', 'one')}
                        className={`p-2.5 rounded-lg border text-xs font-semibold ${getDesignSetting('columns', 'one') === 'one' ? 'bg-brand-600 text-white border-brand-600' : 'bg-white text-neutral-700 border-neutral-200'}`}
                      >
                        Single Column
                      </button>
                      <button
                        onClick={() => updateDesignSetting('columns', 'two')}
                        className={`p-2.5 rounded-lg border text-xs font-semibold ${getDesignSetting('columns', 'one') === 'two' ? 'bg-brand-600 text-white border-brand-600' : 'bg-white text-neutral-700 border-neutral-200'}`}
                      >
                        Two Columns
                      </button>
                    </div>
                    {getDesignSetting('columns', 'one') === 'two' && (
                      <div className="flex gap-4 items-center">
                        <div className="flex-1">
                          <label className="text-[11px] text-neutral-500 block">Left column width (%)</label>
                          <input
                            type="number"
                            value={getDesignSetting('columnWidthLeft', 40)}
                            onChange={(e) => {
                              const val = Math.min(80, Math.max(20, parseInt(e.target.value) || 40))
                              updateDesignSetting('columnWidthLeft', val)
                              updateDesignSetting('columnWidthRight', 100 - val)
                            }}
                            className="w-full mt-1 border border-neutral-200 rounded p-1.5 text-xs text-neutral-800"
                          />
                        </div>
                        <div className="flex-1">
                          <label className="text-[11px] text-neutral-500 block">Right column width (%)</label>
                          <input
                            type="number"
                            value={getDesignSetting('columnWidthRight', 60)}
                            onChange={(e) => {
                              const val = Math.min(80, Math.max(20, parseInt(e.target.value) || 60))
                              updateDesignSetting('columnWidthRight', val)
                              updateDesignSetting('columnWidthLeft', 100 - val)
                            }}
                            className="w-full mt-1 border border-neutral-200 rounded p-1.5 text-xs text-neutral-800"
                          />
                        </div>
                      </div>
                    )}
                  </div>

                  {/* Header Alignment & Layout */}
                  <div className="space-y-3">
                    <label className="text-xs font-bold text-neutral-700 uppercase tracking-wider block">Header Positioning</label>
                    <div className="grid grid-cols-3 gap-2">
                      {['top', 'left', 'right'].map((pos) => (
                        <button
                          key={pos}
                          onClick={() => updateDesignSetting('headerPosition', pos)}
                          className={`p-2 rounded-lg border text-xs capitalize font-semibold ${getDesignSetting('headerPosition', 'top') === pos ? 'bg-brand-600 text-white border-brand-600' : 'bg-white text-neutral-700 border-neutral-200'}`}
                        >
                          {pos}
                        </button>
                      ))}
                    </div>
                  </div>

                  {/* Metadata Separators & Icon styles */}
                  <div className="space-y-3">
                    <label className="text-xs font-bold text-neutral-700 uppercase tracking-wider block">Details Arrangement</label>
                    <div className="grid grid-cols-4 gap-2">
                      {[
                        { id: 'bullet', label: 'Bullet •' },
                        { id: 'pipe', label: 'Pipe |' },
                        { id: 'bar', label: 'Bar /' },
                        { id: 'icon', label: 'Icons' }
                      ].map((item) => (
                        <button
                          key={item.id}
                          onClick={() => updateDesignSetting('detailsArrangement', item.id)}
                          className={`p-1.5 rounded border text-[11px] font-semibold text-center ${getDesignSetting('detailsArrangement', 'bullet') === item.id ? 'bg-brand-600 text-white border-brand-600' : 'bg-white text-neutral-700 border-neutral-200'}`}
                        >
                          {item.label}
                        </button>
                      ))}
                    </div>

                    {getDesignSetting('detailsArrangement', 'bullet') === 'icon' && (
                      <div className="space-y-2">
                        <label className="text-[11px] text-neutral-500 block">Icon Style</label>
                        <select
                          value={getDesignSetting('iconStyle', 'none')}
                          onChange={(e) => updateDesignSetting('iconStyle', e.target.value)}
                          className="w-full border border-neutral-200 rounded p-1.5 text-xs text-neutral-800 bg-white"
                        >
                          <option value="none">No frame</option>
                          <option value="circleFilled">Circle filled</option>
                          <option value="roundedFilled">Rounded filled</option>
                          <option value="squareFilled">Square filled</option>
                          <option value="circleOutline">Circle outline</option>
                          <option value="roundedOutline">Rounded outline</option>
                          <option value="squareOutline">Square outline</option>
                        </select>
                      </div>
                    )}
                  </div>

                  {/* Font Type & Family */}
                  <div className="space-y-3">
                    <label className="text-xs font-bold text-neutral-700 uppercase tracking-wider block">Font Family 🔠</label>
                    <select
                      value={getDesignSetting('fontFamily', 'Montserrat')}
                      onChange={(e) => updateDesignSetting('fontFamily', e.target.value)}
                      className="w-full border border-neutral-200 rounded p-2 text-xs text-neutral-800 bg-white font-medium"
                    >
                      {GOOGLE_FONTS.map((font) => (
                        <option key={font.family} value={font.family}>
                          {font.name}
                        </option>
                      ))}
                    </select>
                  </div>

                  {/* Spacings (margins and line height) */}
                  <div className="space-y-3">
                    <label className="text-xs font-bold text-neutral-700 uppercase tracking-wider block">Spacing & Margins</label>
                    
                    <div className="grid grid-cols-2 gap-3 text-xs">
                      <div>
                        <span className="text-neutral-500 block">Font Size</span>
                        <select
                          value={getDesignSetting('fontSize', '10pt')}
                          onChange={(e) => updateDesignSetting('fontSize', e.target.value)}
                          className="w-full mt-1 border border-neutral-200 rounded p-1.5 bg-white text-neutral-800"
                        >
                          <option value="8.5pt">xs (8.5pt)</option>
                          <option value="9.5pt">s (9.5pt)</option>
                          <option value="10pt">m (10pt)</option>
                          <option value="11pt">l (11pt)</option>
                          <option value="12pt">xl (12pt)</option>
                        </select>
                      </div>

                      <div>
                        <span className="text-neutral-500 block">Line Height</span>
                        <select
                          value={getDesignSetting('lineHeight', '1.4')}
                          onChange={(e) => updateDesignSetting('lineHeight', e.target.value)}
                          className="w-full mt-1 border border-neutral-200 rounded p-1.5 bg-white text-neutral-800"
                        >
                          <option value="1.2">1.2 (Compact)</option>
                          <option value="1.3">1.3</option>
                          <option value="1.4">1.4 (Standard)</option>
                          <option value="1.5">1.5</option>
                          <option value="1.6">1.6 (Wide)</option>
                        </select>
                      </div>
                    </div>

                    <div className="grid grid-cols-2 gap-3 text-xs">
                      <div>
                        <span className="text-neutral-500 block">L/R Margin</span>
                        <select
                          value={getDesignSetting('marginLR', '18mm')}
                          onChange={(e) => updateDesignSetting('marginLR', e.target.value)}
                          className="w-full mt-1 border border-neutral-200 rounded p-1.5 bg-white text-neutral-800"
                        >
                          <option value="10mm">10mm</option>
                          <option value="14mm">14mm</option>
                          <option value="18mm">18mm</option>
                          <option value="22mm">22mm</option>
                          <option value="26mm">26mm</option>
                        </select>
                      </div>

                      <div>
                        <span className="text-neutral-500 block">T/B Margin</span>
                        <select
                          value={getDesignSetting('marginTB', '16mm')}
                          onChange={(e) => updateDesignSetting('marginTB', e.target.value)}
                          className="w-full mt-1 border border-neutral-200 rounded p-1.5 bg-white text-neutral-800"
                        >
                          <option value="10mm">10mm</option>
                          <option value="14mm">14mm</option>
                          <option value="16mm">16mm</option>
                          <option value="20mm">20mm</option>
                          <option value="24mm">24mm</option>
                        </select>
                      </div>
                    </div>
                  </div>

                  {/* Header Name sizes */}
                  <div className="space-y-3">
                    <label className="text-xs font-bold text-neutral-700 uppercase tracking-wider block">Header Name Settings</label>
                    <div className="flex gap-4 items-center">
                      <div className="flex-1">
                        <span className="text-[11px] text-neutral-500 block">Name Size</span>
                        <select
                          value={getDesignSetting('nameSize', 'l')}
                          onChange={(e) => updateDesignSetting('nameSize', e.target.value)}
                          className="w-full mt-1 border border-neutral-200 rounded p-1.5 bg-white text-neutral-800 text-xs"
                        >
                          <option value="xs">xs</option>
                          <option value="s">s</option>
                          <option value="m">m</option>
                          <option value="l">l</option>
                          <option value="xl">xl</option>
                        </select>
                      </div>
                      <div className="flex items-center gap-2 mt-4">
                        <input
                          type="checkbox"
                          id="name-bold"
                          checked={getDesignSetting('nameBold', true)}
                          onChange={(e) => updateDesignSetting('nameBold', e.target.checked)}
                          className="rounded text-brand-600"
                        />
                        <label htmlFor="name-bold" className="text-xs text-neutral-700 font-semibold cursor-pointer">Bold Name</label>
                      </div>
                    </div>
                  </div>

                  {/* Photo Customizations */}
                  {resume.photoUrl && (
                    <div className="space-y-3 border border-neutral-200 p-3 rounded-lg bg-neutral-50">
                      <span className="block text-[11px] font-bold text-neutral-700 uppercase">Photo Options 📸</span>
                      
                      <div className="grid grid-cols-2 gap-3 text-xs">
                        <div>
                          <span className="text-neutral-500 block">Photo Style</span>
                          <select
                            value={getDesignSetting('photoStyle', 'circle')}
                            onChange={(e) => updateDesignSetting('photoStyle', e.target.value)}
                            className="w-full mt-1 border border-neutral-200 rounded p-1.5 bg-white text-neutral-800"
                          >
                            <option value="square">Square</option>
                            <option value="rounded">Rounded</option>
                            <option value="circle">Circle</option>
                          </select>
                        </div>
                        <div>
                          <span className="text-neutral-500 block">Photo Alignment</span>
                          <select
                            value={getDesignSetting('photoAlignment', 'left')}
                            onChange={(e) => updateDesignSetting('photoAlignment', e.target.value)}
                            className="w-full mt-1 border border-neutral-200 rounded p-1.5 bg-white text-neutral-800"
                          >
                            <option value="left">Left</option>
                            <option value="center">Center</option>
                            <option value="right">Right</option>
                          </select>
                        </div>
                      </div>

                      <div className="grid grid-cols-2 gap-3 text-xs">
                        <div>
                          <span className="text-neutral-500 block">Size (px)</span>
                          <input
                            type="number"
                            value={getDesignSetting('photoSize', 90)}
                            onChange={(e) => updateDesignSetting('photoSize', Math.min(180, Math.max(40, parseInt(e.target.value) || 90)))}
                            className="w-full mt-1 border border-neutral-200 rounded p-1.5 text-neutral-800"
                          />
                        </div>
                        <div className="flex items-center gap-2 mt-4">
                          <input
                            type="checkbox"
                            id="photo-border"
                            checked={getDesignSetting('photoBorder', true)}
                            onChange={(e) => updateDesignSetting('photoBorder', e.target.checked)}
                            className="rounded text-brand-600"
                          />
                          <label htmlFor="photo-border" className="text-xs text-neutral-700 font-semibold cursor-pointer">Show Border</label>
                        </div>
                      </div>
                    </div>
                  )}

                  {/* Link Styling Settings */}
                  <div className="space-y-3">
                    <label className="text-xs font-bold text-neutral-700 uppercase tracking-wider block">Link Styling 🔗</label>
                    <div className="space-y-2 text-xs">
                      <label className="flex items-center gap-2 text-neutral-700 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={getDesignSetting('linkUnderline', true)}
                          onChange={(e) => updateDesignSetting('linkUnderline', e.target.checked)}
                          className="rounded text-brand-600"
                        />
                        Underline Links
                      </label>
                      <label className="flex items-center gap-2 text-neutral-700 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={getDesignSetting('linkBlueColor', true)}
                          onChange={(e) => updateDesignSetting('linkBlueColor', e.target.checked)}
                          className="rounded text-brand-600"
                        />
                        Use Blue color (or custom Accent color if unchecked)
                      </label>
                      <label className="flex items-center gap-2 text-neutral-700 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={getDesignSetting('linkIcon', true)}
                          onChange={(e) => updateDesignSetting('linkIcon', e.target.checked)}
                          className="rounded text-brand-600"
                        />
                        Show Link Icon
                      </label>
                    </div>
                  </div>

                  {/* Footers options */}
                  <div className="space-y-3">
                    <label className="text-xs font-bold text-neutral-700 uppercase tracking-wider block">Footer Options</label>
                    <div className="space-y-2 text-xs">
                      <label className="flex items-center gap-2 text-neutral-700 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={getDesignSetting('footerPageNumbers', false)}
                          onChange={(e) => updateDesignSetting('footerPageNumbers', e.target.checked)}
                          className="rounded text-brand-600"
                        />
                        Show Page Numbers
                      </label>
                      <label className="flex items-center gap-2 text-neutral-700 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={getDesignSetting('footerName', false)}
                          onChange={(e) => updateDesignSetting('footerName', e.target.checked)}
                          className="rounded text-brand-600"
                        />
                        Show Name in Footer
                      </label>
                      <label className="flex items-center gap-2 text-neutral-700 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={getDesignSetting('footerEmail', false)}
                          onChange={(e) => updateDesignSetting('footerEmail', e.target.checked)}
                          className="rounded text-brand-600"
                        />
                        Show Email in Footer
                      </label>
                    </div>
                  </div>

                  {/* Share Design template helper */}
                  {savedId && (
                    <div className="border border-brand-200 p-4 rounded-xl space-y-2 bg-brand-50/50">
                      <h4 className="text-xs font-bold text-brand-900 flex items-center gap-1">
                        <span>💡 Share design as a template</span>
                      </h4>
                      <p className="text-[11px] text-neutral-500">Create a reusable template based on your customization settings that you can share with friends via a private link.</p>
                      <div className="flex gap-2 pt-1">
                        <Button size="sm" variant="secondary" onClick={copyShareLink}>
                          {copiedLink ? 'Copied! ✅' : 'Copy Private Share Link'}
                        </Button>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Right: Preview */}
        <div className="flex-1 overflow-auto bg-neutral-200 flex items-start justify-center p-8 print-only-content">
          <div className="shadow-2xl">
            <ResumePreview data={resume} />
          </div>
        </div>
      </div>
    </div>
  )
}
