// Beautify Studio — a mini Canva-style resume designer.
// Self-contained: relies on globals (React hooks, Icon/Btn/Wordmark, SAMPLE_RESUME, atsScore).

const BEAUTIFY_FONTS = [
  { id: 'poppins', label: 'Poppins', stack: "'Poppins', system-ui, sans-serif" },
  { id: 'inter', label: 'Inter', stack: "'Inter', system-ui, sans-serif" },
  { id: 'instrument', label: 'Instrument', stack: "'Instrument Serif', Georgia, serif" },
  { id: 'jetbrains', label: 'JetBrains', stack: "'JetBrains Mono', ui-monospace, monospace" },
  { id: 'georgia', label: 'Georgia', stack: "Georgia, 'Times New Roman', serif" },
];
const fontStack = (id) => (BEAUTIFY_FONTS.find(f => f.id === id) || BEAUTIFY_FONTS[0]).stack;

// Each template maps to a structural layout + a few preset knobs (not colors).
const BEAUTIFY_TEMPLATES = [
  { id: 'sidebar-left', name: 'Sidebar L', layout: 'sidebar', opts: { sidebarSide: 'left', headerStyle: 'bar' } },
  { id: 'sidebar-right', name: 'Sidebar R', layout: 'sidebar', opts: { sidebarSide: 'right', headerStyle: 'bar' } },
  { id: 'classic', name: 'Classic', layout: 'stacked', opts: { headerStyle: 'underline', headerAlign: 'left' } },
  { id: 'banner', name: 'Banner', layout: 'band', opts: { headerStyle: 'bar' } },
  { id: 'modern', name: 'Modern', layout: 'stacked', opts: { headerAlign: 'center', headerStyle: 'plain', accentName: true } },
  { id: 'twocol', name: 'Two-Col', layout: 'twocolbody', opts: { headerStyle: 'bar', headerAlign: 'left' } },
  { id: 'compact', name: 'Compact', layout: 'twocolbody', opts: { headerStyle: 'underline', sectionGap: 12, fontScale: 0.92 } },
  { id: 'timeline', name: 'Timeline', layout: 'timeline', opts: { headerStyle: 'bar' } },
  { id: 'elegant', name: 'Elegant', layout: 'stacked', opts: { headerAlign: 'center', headerStyle: 'underline', headingFont: 'instrument', uppercaseHeads: false } },
  { id: 'editorial', name: 'Editorial', layout: 'stacked', opts: { headerStyle: 'underline', headingFont: 'instrument', headerAlign: 'left', uppercaseHeads: false, nameScale: 1.12 } },
  { id: 'minimal', name: 'Minimal', layout: 'stacked', opts: { headerStyle: 'plain', uppercaseHeads: false, sectionGap: 22 } },
  { id: 'bold', name: 'Bold', layout: 'band', opts: { headerStyle: 'bar', nameScale: 1.18 } },
];
const templateLayout = (id) => (BEAUTIFY_TEMPLATES.find(t => t.id === id) || BEAUTIFY_TEMPLATES[0]).layout;

const ACCENTS = ['#6CB274', '#1E3A8A', '#0F766E', '#7C3AED', '#E11D48', '#EA580C', '#0EA5E9', '#1A1A1A', '#B45309', '#DB2777', '#2563EB', '#059669'];
const BACKGROUNDS = ['#FFFFFF', '#FAFAF7', '#F7F2EE', '#F2F6F3', '#F4F4F8', '#FFF7FB'];
const SECTION_LABELS = { summary: 'Summary', experience: 'Experience', skills: 'Skills', education: 'Education', projects: 'Projects' };

const THEMES = [
  { name: 'Sage Sidebar', opts: { template: 'sidebar-left', accent: '#6CB274', bg: '#FFFFFF', headingFont: 'poppins', bodyFont: 'poppins', headerStyle: 'bar', sidebarStyle: 'solid' } },
  { name: 'Navy Pro', opts: { template: 'sidebar-left', accent: '#1E3A8A', bg: '#FFFFFF', headerStyle: 'bar', sidebarStyle: 'solid' } },
  { name: 'Editorial', opts: { template: 'editorial', accent: '#1A1A1A', bg: '#FAFAF7', headingFont: 'instrument', bodyFont: 'georgia', headerStyle: 'underline', uppercaseHeads: false } },
  { name: 'Modern Teal', opts: { template: 'modern', accent: '#0F766E', bg: '#FFFFFF', headerAlign: 'center', headerStyle: 'plain', accentName: true } },
  { name: 'Banner Bold', opts: { template: 'bold', accent: '#EA580C', bg: '#FFFFFF', headerStyle: 'bar', nameScale: 1.18 } },
  { name: 'Minimal Mono', opts: { template: 'minimal', accent: '#1A1A1A', bg: '#FFFFFF', headingFont: 'jetbrains', bodyFont: 'inter', headerStyle: 'plain', bulletStyle: 'dash' } },
  { name: 'Violet Grid', opts: { template: 'twocol', accent: '#7C3AED', bg: '#FFFFFF', headerStyle: 'bar' } },
  { name: 'Timeline Sky', opts: { template: 'timeline', accent: '#0EA5E9', bg: '#FFFFFF', headerStyle: 'bar' } },
  { name: 'Rose Elegant', opts: { template: 'elegant', accent: '#DB2777', bg: '#FFF7FB', headingFont: 'instrument', bodyFont: 'georgia', headerStyle: 'underline', uppercaseHeads: false } },
  { name: 'Warm Right', opts: { template: 'sidebar-right', accent: '#B45309', bg: '#FFFDF7', headerStyle: 'bar' } },
];

const DEFAULT_OPTS = {
  template: 'sidebar-left',
  accent: '#6CB274', bg: '#FFFFFF',
  headingFont: 'poppins', bodyFont: 'poppins',
  fontScale: 1, lineHeight: 1.5, headLetterSpacing: 0.12,
  margin: 40, sectionGap: 18, nameScale: 1, sidebarWidth: 230,
  headerStyle: 'bar', headerAlign: 'left', sidebarSide: 'left', sidebarStyle: 'solid',
  uppercaseHeads: true, accentName: false, accentHeaderBg: false, divider: false,
  bulletStyle: 'dot', skillStyle: 'pills',
  showPhoto: false, photoShape: 'circle',
  showLocation: true, showLinks: true,
  paper: 'letter',
  sections: ['summary', 'experience', 'skills', 'education', 'projects'], hidden: {},
};

// ---------------------------------------------------------------------------
function BeautifyDoc({ data, opts }) {
  const o = { ...DEFAULT_OPTS, ...opts };
  const layout = templateLayout(o.template);
  const headingFont = fontStack(o.headingFont);
  const bodyFont = fontStack(o.bodyFont);
  const accent = o.accent;
  const fs = (n) => `${(n * o.fontScale).toFixed(1)}px`;
  const lh = o.lineHeight;
  const ls = `${o.headLetterSpacing}em`;
  const heads = (t) => (o.uppercaseHeads ? t.toUpperCase() : t);
  const initials = (data.name || 'You').split(' ').map(s => s[0]).slice(0, 2).join('').toUpperCase();
  const role = (data.experience && data.experience[0] && data.experience[0].title) || '';
  const order = o.sections.filter(s => !o.hidden[s]);
  const bulletChar = { dot: '•', dash: '–', arrow: '→', none: '' }[o.bulletStyle];

  const SecHead = ({ children, light }) => {
    const color = light ? '#fff' : accent;
    const txt = heads(children);
    if (o.accentHeaderBg) return <div style={{ display: 'inline-block', background: light ? 'rgba(255,255,255,0.22)' : accent, color: '#fff', padding: '3px 9px', borderRadius: 4, fontSize: fs(10.5), fontWeight: 700, letterSpacing: ls, marginBottom: 8 }}>{txt}</div>;
    if (o.headerStyle === 'bar') return <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}><span style={{ width: 14, height: 3, background: color, borderRadius: 2 }}/><span style={{ fontSize: fs(10.5), fontWeight: 700, letterSpacing: ls, color }}>{txt}</span></div>;
    if (o.headerStyle === 'underline') return <div style={{ fontSize: fs(10.5), fontWeight: 700, letterSpacing: ls, color, borderBottom: `1.5px solid ${color}`, paddingBottom: 3, marginBottom: 8 }}>{txt}</div>;
    return <div style={{ fontSize: fs(10.5), fontWeight: 700, letterSpacing: ls, color, marginBottom: 8, borderBottom: o.divider ? `1px solid ${light ? 'rgba(255,255,255,0.3)' : '#e5e3de'}` : 'none', paddingBottom: o.divider ? 3 : 0 }}>{txt}</div>;
  };

  const Bullets = ({ items, light }) => <div>
    {(items || []).map((b, j) => (
      <div key={j} style={{ display: 'flex', gap: 6, fontSize: fs(11), lineHeight: lh, marginBottom: 2, color: light ? '#fff' : '#333' }}>
        {o.bulletStyle !== 'none' && <span style={{ color: light ? '#fff' : accent, flexShrink: 0 }}>{bulletChar}</span>}
        <span>{b}</span>
      </div>
    ))}
  </div>;

  const Summary = ({ light }) => data.summary ? <p style={{ fontSize: fs(11.5), lineHeight: lh, color: light ? '#fff' : '#333', margin: 0 }}>{data.summary}</p> : null;
  const Experience = ({ light }) => <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
    {(data.experience || []).map((e, i) => (
      <div key={i}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <span style={{ fontSize: fs(12.5), fontWeight: 600, color: light ? '#fff' : '#1a1a1a' }}>{e.title}</span>
          <span style={{ fontSize: fs(10), color: light ? 'rgba(255,255,255,0.8)' : '#666' }}>{e.dates}</span>
        </div>
        <div style={{ fontSize: fs(11), color: light ? 'rgba(255,255,255,0.9)' : accent, marginBottom: 4 }}>{[e.company, e.location].filter(Boolean).join(' · ')}</div>
        <Bullets items={e.bullets} light={light}/>
      </div>
    ))}
  </div>;
  const TimelineExp = () => <div style={{ position: 'relative', paddingLeft: 20, borderLeft: `2px solid ${accent}40` }}>
    {(data.experience || []).map((e, i) => (
      <div key={i} style={{ position: 'relative', marginBottom: 12 }}>
        <span style={{ position: 'absolute', left: -27, top: 3, width: 10, height: 10, borderRadius: '50%', background: accent, border: '2px solid #fff' }}/>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <span style={{ fontSize: fs(12.5), fontWeight: 600 }}>{e.title}</span>
          <span style={{ fontSize: fs(10), color: '#666' }}>{e.dates}</span>
        </div>
        <div style={{ fontSize: fs(11), color: accent, marginBottom: 4 }}>{[e.company, e.location].filter(Boolean).join(' · ')}</div>
        <Bullets items={e.bullets}/>
      </div>
    ))}
  </div>;
  const Projects = ({ light }) => <div>{(data.projects || []).map((p, i) => <div key={i} style={{ fontSize: fs(11), lineHeight: lh, marginBottom: 4, color: light ? '#fff' : '#333' }}><span style={{ fontWeight: 600 }}>{p.name}</span> <span style={{ color: light ? 'rgba(255,255,255,0.85)' : '#666' }}>— {p.desc}{p.year ? ` (${p.year})` : ''}</span></div>)}</div>;
  const Education = ({ light }) => <div>{(data.education || []).map((ed, i) => <div key={i} style={{ fontSize: fs(11), lineHeight: lh, marginBottom: 6 }}><div style={{ fontWeight: 600, color: light ? '#fff' : '#1a1a1a' }}>{ed.school}</div><div style={{ color: light ? 'rgba(255,255,255,0.85)' : '#555' }}>{ed.degree}{ed.year ? ` · ${ed.year}` : ''}</div></div>)}</div>;
  const Skills = ({ light }) => {
    const sk = data.skills || [];
    if (o.skillStyle === 'comma') return <div style={{ fontSize: fs(11), lineHeight: lh, color: light ? '#fff' : '#333' }}>{sk.join(' · ')}</div>;
    if (o.skillStyle === 'list') return <div>{sk.map(s => <div key={s} style={{ fontSize: fs(11), lineHeight: lh, color: light ? '#fff' : '#333' }}>{s}</div>)}</div>;
    return <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>{sk.map(s => <span key={s} style={{ fontSize: fs(10), padding: '3px 8px', borderRadius: 999, background: light ? 'rgba(255,255,255,0.18)' : 'rgba(0,0,0,0.05)', color: light ? '#fff' : '#333' }}>{s}</span>)}</div>;
  };
  const contactLines = [
    o.showLocation ? data.location : null, data.phone, data.email,
    ...(o.showLinks ? (data.links || []) : []),
  ].filter(Boolean);
  const Contact = ({ light }) => <div style={{ fontSize: fs(10.5), lineHeight: 1.6, color: light ? '#fff' : '#444' }}>
    {contactLines.map((l, i) => <div key={i}>{l}</div>)}
  </div>;

  const present = (id) => ({
    summary: !!data.summary,
    experience: (data.experience || []).length > 0,
    projects: (data.projects || []).length > 0,
    skills: (data.skills || []).length > 0,
    education: (data.education || []).length > 0,
  })[id];
  const Body = ({ id, light }) => ({
    summary: <Summary light={light}/>, experience: <Experience light={light}/>,
    projects: <Projects light={light}/>, skills: <Skills light={light}/>, education: <Education light={light}/>,
  })[id] || null;
  const renderSec = (id, light, timeline) => present(id) ? (
    <div key={id} style={{ marginBottom: o.sectionGap }}>
      <SecHead light={light}>{SECTION_LABELS[id]}</SecHead>
      {timeline && id === 'experience' ? <TimelineExp/> : <Body id={id} light={light}/>}
    </div>
  ) : null;

  const Photo = ({ size, light }) => o.showPhoto ? <div style={{ width: size, height: size, borderRadius: o.photoShape === 'circle' ? '50%' : o.photoShape === 'rounded' ? 16 : 4, background: light ? 'rgba(255,255,255,0.2)' : 'var(--bg-sunken)', border: light ? '2px solid rgba(255,255,255,0.3)' : '1px solid #e5e3de', color: light ? '#fff' : '#888', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: size * 0.38, fontWeight: 700, margin: o.headerAlign === 'center' ? '0 auto 14px' : '0 0 14px' }}>{initials}</div> : null;

  const NameBlock = ({ light, center }) => <div style={{ textAlign: center ? 'center' : 'left' }}>
    <div style={{ fontSize: fs(34 * o.nameScale), fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1.05, color: light ? '#fff' : (o.accentName ? accent : '#1a1a1a'), fontFamily: headingFont }}>{data.name}</div>
    {role && <div style={{ fontSize: fs(13), color: light ? 'rgba(255,255,255,0.9)' : accent, fontWeight: 500, marginTop: 4 }}>{role}</div>}
  </div>;

  const minH = o.paper === 'a4' ? 1018 : 932;
  const page = { background: o.bg, fontFamily: bodyFont, color: '#1a1a1a', borderRadius: 4, boxShadow: 'var(--shadow-lg)', overflow: 'hidden', minHeight: minH };

  // ---- layouts ----
  if (layout === 'sidebar') {
    const tint = o.sidebarStyle === 'tint';
    const sideBg = tint ? `${accent}14` : accent;
    const sideLight = !tint;
    const sideSecs = order.filter(s => s === 'skills' || s === 'education');
    const mainSecs = order.filter(s => s === 'summary' || s === 'experience' || s === 'projects');
    const sidebar = <div style={{ background: sideBg, color: sideLight ? '#fff' : '#333', padding: Math.round(o.margin * 0.7), width: o.sidebarWidth, flexShrink: 0 }}>
      <Photo light={sideLight} size={96}/>
      <div style={{ marginBottom: o.sectionGap }}><SecHead light={sideLight}>Contact</SecHead><Contact light={sideLight}/></div>
      {sideSecs.map(id => renderSec(id, sideLight))}
    </div>;
    const main = <div style={{ padding: o.margin, flex: 1, minWidth: 0 }}>
      <div style={{ marginBottom: o.sectionGap }}><NameBlock/></div>
      {mainSecs.map(id => renderSec(id, false))}
    </div>;
    return <div style={{ ...page, display: 'flex', flexDirection: o.sidebarSide === 'right' ? 'row-reverse' : 'row' }}>{sidebar}{main}</div>;
  }

  if (layout === 'band') {
    return <div style={page}>
      <div style={{ background: accent, color: '#fff', padding: `${Math.round(o.margin * 0.7)}px ${o.margin}px`, display: 'flex', alignItems: 'center', gap: 20 }}>
        <Photo light size={72}/>
        <div><NameBlock light/><div style={{ marginTop: 8 }}><Contact light/></div></div>
      </div>
      <div style={{ padding: o.margin }}>{order.map(id => renderSec(id, false))}</div>
    </div>;
  }

  if (layout === 'twocolbody') {
    const left = order.filter(s => s === 'experience' || s === 'projects');
    const right = order.filter(s => s === 'skills' || s === 'education');
    return <div style={page}>
      <div style={{ padding: o.margin }}>
        <div style={{ marginBottom: o.sectionGap }}>
          <NameBlock/>
          <div style={{ marginTop: 8 }}><Contact/></div>
          <div style={{ height: 3, background: accent, width: '100%', margin: '12px 0 0', borderRadius: 2 }}/>
        </div>
        {order.includes('summary') && renderSec('summary', false)}
        <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: Math.round(o.margin * 0.6) }}>
          <div>{left.map(id => renderSec(id, false))}</div>
          <div>{right.map(id => renderSec(id, false))}</div>
        </div>
      </div>
    </div>;
  }

  if (layout === 'timeline') {
    return <div style={page}>
      <div style={{ padding: o.margin }}>
        <div style={{ marginBottom: o.sectionGap }}>
          <NameBlock/>
          <div style={{ marginTop: 8 }}><Contact/></div>
          <div style={{ height: 3, background: accent, width: '100%', margin: '12px 0 0', borderRadius: 2 }}/>
        </div>
        {order.map(id => renderSec(id, false, true))}
      </div>
    </div>;
  }

  // stacked (classic / modern / elegant / editorial / minimal)
  const center = o.headerAlign === 'center';
  return <div style={page}>
    <div style={{ padding: o.margin }}>
      <div style={{ marginBottom: o.sectionGap, textAlign: center ? 'center' : 'left' }}>
        {center && <Photo size={88}/>}
        <NameBlock center={center}/>
        <div style={{ marginTop: 8, display: 'flex', justifyContent: center ? 'center' : 'flex-start' }}><Contact/></div>
        <div style={{ height: 3, background: accent, width: center ? 80 : '100%', margin: center ? '14px auto 0' : '12px 0 0', borderRadius: 2 }}/>
      </div>
      {order.map(id => renderSec(id, false))}
    </div>
  </div>;
}

// ---- studio controls ----
function Slider({ label, value, min, max, step = 1, fmt, onChange }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
        <span className="t-body-sm" style={{ fontWeight: 500 }}>{label}</span>
        <span className="t-body-sm muted">{fmt ? fmt(value) : value}</span>
      </div>
      <input type="range" min={min} max={max} step={step} value={value} onChange={e => onChange(Number(e.target.value))} style={{ width: '100%', accentColor: 'var(--accent-primary)' }}/>
    </div>
  );
}
function Segmented({ value, options, onChange, label }) {
  return (
    <div style={{ marginBottom: 14 }}>
      {label && <div className="t-body-sm" style={{ fontWeight: 500, marginBottom: 8 }}>{label}</div>}
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {options.map(([val, lbl]) => (
          <button key={val} onClick={() => onChange(val)} style={{
            flex: '1 1 0', minWidth: 56, padding: '8px 6px', borderRadius: 8, cursor: 'pointer', fontFamily: 'inherit', fontSize: 12,
            border: `1.5px solid ${value === val ? 'var(--accent-primary)' : 'var(--border-default)'}`,
            background: value === val ? 'rgba(var(--accent-rgb),0.06)' : 'var(--bg-surface)',
          }}>{lbl}</button>
        ))}
      </div>
    </div>
  );
}
function BToggle({ label, checked, onChange }) {
  return (
    <button onClick={() => onChange(!checked)} style={{
      display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px',
      border: '1px solid var(--border-default)', borderRadius: 8, background: 'var(--bg-surface)',
      cursor: 'pointer', fontFamily: 'inherit', width: '100%', textAlign: 'left',
    }}>
      <span style={{ flex: 1, fontSize: 13 }}>{label}</span>
      <span style={{ width: 36, height: 20, borderRadius: 999, background: checked ? 'var(--accent-primary)' : 'var(--border-strong)', position: 'relative', transition: 'background var(--d-fast)' }}>
        <span style={{ position: 'absolute', top: 2, left: checked ? 18 : 2, width: 16, height: 16, borderRadius: '50%', background: '#fff', transition: 'left var(--d-fast)' }}/>
      </span>
    </button>
  );
}

function BeautifyMini({ id, accent }) {
  const layout = templateLayout(id);
  const line = (w, c = '#ddd', h = 2) => ({ height: h, background: c, margin: '2px 0', width: `${w}%`, borderRadius: 1 });
  if (layout === 'sidebar') {
    const rev = id === 'sidebar-right';
    return <div style={{ display: 'flex', flexDirection: rev ? 'row-reverse' : 'row', gap: 4, height: '100%' }}>
      <div style={{ width: '30%', background: accent, borderRadius: 2 }}/>
      <div style={{ flex: 1 }}>
        <div style={{ height: 6, width: '60%', background: '#111', borderRadius: 2 }}/>
        {[80, 70, 85, 65, 80, 75].map((w, i) => <div key={i} style={line(w)}/>)}
      </div>
    </div>;
  }
  if (layout === 'band') return <>
    <div style={{ height: 16, background: accent, borderRadius: 2, marginBottom: 4 }}/>
    {[90, 80, 70, 85, 75, 80].map((w, i) => <div key={i} style={line(w)}/>)}
  </>;
  if (layout === 'twocolbody') return <>
    <div style={{ height: 6, width: '50%', background: '#111', borderRadius: 2 }}/>
    <div style={{ height: 2, width: '100%', background: accent, margin: '4px 0' }}/>
    <div style={{ display: 'flex', gap: 4 }}>
      <div style={{ flex: 1.5 }}>{[95, 90, 92, 85].map((w, i) => <div key={i} style={line(w, '#ddd', 1.5)}/>)}</div>
      <div style={{ flex: 1 }}>{[80, 70, 75].map((w, i) => <div key={i} style={line(w, '#e5e5e5', 1.5)}/>)}</div>
    </div>
  </>;
  if (layout === 'timeline') return <div style={{ paddingLeft: 8, borderLeft: `2px solid ${accent}` }}>
    <div style={{ height: 6, width: '50%', background: '#111', borderRadius: 2 }}/>
    {[85, 90, 75, 88].map((w, i) => <div key={i} style={line(w)}/>)}
  </div>;
  // stacked
  const center = (BEAUTIFY_TEMPLATES.find(t => t.id === id)?.opts.headerAlign) === 'center';
  return <div style={{ textAlign: center ? 'center' : 'left' }}>
    <div style={{ height: 8, width: '55%', background: id === 'modern' ? accent : '#111', borderRadius: 2, margin: center ? '2px auto 0' : 0 }}/>
    <div style={{ height: 2, width: center ? 24 : '80%', background: accent, margin: center ? '5px auto' : '5px 0' }}/>
    {[85, 90, 75, 88, 70].map((w, i) => <div key={i} style={{ ...line(w), marginLeft: center ? 'auto' : 0, marginRight: center ? 'auto' : 0 }}/>)}
  </div>;
}

function BeautifyScreen({ go, resume }) {
  const data = resume || SAMPLE_RESUME;
  const [opts, setOpts] = useState({ ...DEFAULT_OPTS });
  const [tab, setTab] = useState('Themes');
  const [zoom, setZoom] = useState(58);
  const set = (k, v) => setOpts(o => ({ ...o, [k]: v }));
  const score = atsScore(data);
  const fileBase = (data.name || 'Resume').replace(/\s+/g, '_');

  const pickTemplate = (t) => setOpts(o => ({ ...o, template: t.id, ...t.opts }));
  const pickTheme = (th) => setOpts({ ...DEFAULT_OPTS, ...th.opts });
  const moveSection = (id, dir) => setOpts(o => {
    const arr = [...o.sections]; const i = arr.indexOf(id); const j = i + dir;
    if (j < 0 || j >= arr.length) return o;
    [arr[i], arr[j]] = [arr[j], arr[i]];
    return { ...o, sections: arr };
  });
  const toggleHidden = (id) => setOpts(o => ({ ...o, hidden: { ...o.hidden, [id]: !o.hidden[id] } }));
  const isSidebar = templateLayout(opts.template) === 'sidebar';

  const TABS = ['Themes', 'Template', 'Color', 'Fonts', 'Layout', 'Sections'];

  return (
    <div style={{ height: '100vh', display: 'grid', gridTemplateColumns: '360px 1fr 240px', background: 'var(--bg-canvas)' }}>
      {/* Left rail */}
      <aside style={{ borderRight: '1px solid var(--border-default)', background: 'var(--bg-surface)', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
        <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--border-default)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <button onClick={() => go('export')} style={{ background: 'transparent', border: 0, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, fontFamily: 'inherit', color: 'var(--text-secondary)', fontSize: 13 }}>
            <Icon.arrowLeft size={14}/> Back
          </button>
          <Wordmark size="sm"/>
        </div>

        <div style={{ display: 'flex', borderBottom: '1px solid var(--border-default)' }}>
          {TABS.map(t => (
            <button key={t} onClick={() => setTab(t)} style={{
              flex: 1, background: 'transparent', border: 0, padding: '13px 0', cursor: 'pointer', fontFamily: 'inherit', fontSize: 11, fontWeight: 500,
              color: tab === t ? 'var(--accent-primary)' : 'var(--text-secondary)',
              borderBottom: tab === t ? '2px solid var(--accent-primary)' : '2px solid transparent', marginBottom: -1,
            }}>{t}</button>
          ))}
        </div>

        <div className="scroll" style={{ padding: 24, overflowY: 'auto', flex: 1, minHeight: 0 }}>
          {tab === 'Themes' && (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              {THEMES.map(th => (
                <button key={th.name} onClick={() => pickTheme(th)} style={{ padding: 0, border: '1px solid var(--border-default)', borderRadius: 10, overflow: 'hidden', cursor: 'pointer', background: th.opts.bg || '#fff', textAlign: 'left' }}>
                  <div style={{ height: 70, padding: 8 }}><BeautifyMini id={th.opts.template} accent={th.opts.accent}/></div>
                  <div style={{ padding: '8px 10px', borderTop: '1px solid var(--border-default)', background: 'var(--bg-surface)', fontSize: 12, fontWeight: 500 }}>{th.name}</div>
                </button>
              ))}
            </div>
          )}

          {tab === 'Template' && (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, rowGap: 34 }}>
              {BEAUTIFY_TEMPLATES.map(t => (
                <div key={t.id} className={`template-thumb ${opts.template === t.id ? 'selected' : ''}`} onClick={() => pickTemplate(t)}>
                  <div style={{ width: '100%', height: '100%', background: '#fff', borderRadius: 4, padding: 6, position: 'relative', overflow: 'hidden' }}>
                    <BeautifyMini id={t.id} accent={opts.accent}/>
                  </div>
                  <div style={{ position: 'absolute', bottom: -22, left: 0, right: 0, textAlign: 'center', fontSize: 11.5, fontWeight: 500 }}>{t.name}</div>
                </div>
              ))}
            </div>
          )}

          {tab === 'Color' && (
            <div>
              <div className="t-body-sm" style={{ fontWeight: 500, marginBottom: 10 }}>Accent</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
                {ACCENTS.map(c => (
                  <button key={c} onClick={() => set('accent', c)} title={c} style={{ width: 28, height: 28, borderRadius: 8, background: c, cursor: 'pointer', border: opts.accent.toLowerCase() === c.toLowerCase() ? '2px solid var(--text-primary)' : '1px solid var(--border-default)' }}/>
                ))}
                <label style={{ width: 28, height: 28, borderRadius: 8, border: '1px dashed var(--border-strong)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', position: 'relative' }}>
                  <Icon.plus size={14}/>
                  <input type="color" value={opts.accent} onChange={e => set('accent', e.target.value)} style={{ position: 'absolute', inset: 0, opacity: 0, cursor: 'pointer' }}/>
                </label>
              </div>

              <div className="t-body-sm" style={{ fontWeight: 500, margin: '24px 0 10px' }}>Background</div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
                {BACKGROUNDS.map(c => (
                  <button key={c} onClick={() => set('bg', c)} style={{ width: 40, height: 28, borderRadius: 8, background: c, cursor: 'pointer', border: opts.bg.toLowerCase() === c.toLowerCase() ? '2px solid var(--accent-primary)' : '1px solid var(--border-default)' }}/>
                ))}
                <label style={{ width: 28, height: 28, borderRadius: 8, border: '1px dashed var(--border-strong)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', position: 'relative' }}>
                  <Icon.plus size={14}/>
                  <input type="color" value={opts.bg} onChange={e => set('bg', e.target.value)} style={{ position: 'absolute', inset: 0, opacity: 0, cursor: 'pointer' }}/>
                </label>
              </div>

              {isSidebar && <div style={{ marginTop: 20 }}><Segmented label="Sidebar style" value={opts.sidebarStyle} options={[['solid', 'Solid'], ['tint', 'Tint']]} onChange={v => set('sidebarStyle', v)}/></div>}

              <div style={{ marginTop: 18 }} className="stack-sm">
                <BToggle label="Color the name in accent" checked={opts.accentName} onChange={v => set('accentName', v)}/>
                <BToggle label="Filled accent headings" checked={opts.accentHeaderBg} onChange={v => set('accentHeaderBg', v)}/>
                <BToggle label="Show photo monogram" checked={opts.showPhoto} onChange={v => set('showPhoto', v)}/>
              </div>
            </div>
          )}

          {tab === 'Fonts' && (
            <div>
              <div className="t-body-sm" style={{ fontWeight: 500, marginBottom: 10 }}>Heading font</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                {BEAUTIFY_FONTS.map(f => (
                  <button key={f.id} onClick={() => set('headingFont', f.id)} style={{ padding: '10px 8px', borderRadius: 8, cursor: 'pointer', textAlign: 'left', fontFamily: f.stack, fontSize: 14, border: `1.5px solid ${opts.headingFont === f.id ? 'var(--accent-primary)' : 'var(--border-default)'}`, background: 'var(--bg-surface)' }}>{f.label}</button>
                ))}
              </div>
              <div className="t-body-sm" style={{ fontWeight: 500, margin: '20px 0 10px' }}>Body font</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                {BEAUTIFY_FONTS.map(f => (
                  <button key={f.id} onClick={() => set('bodyFont', f.id)} style={{ padding: '10px 8px', borderRadius: 8, cursor: 'pointer', textAlign: 'left', fontFamily: f.stack, fontSize: 14, border: `1.5px solid ${opts.bodyFont === f.id ? 'var(--accent-primary)' : 'var(--border-default)'}`, background: 'var(--bg-surface)' }}>{f.label}</button>
                ))}
              </div>
              <div style={{ marginTop: 24 }}>
                <Slider label="Font size" value={opts.fontScale} min={0.85} max={1.2} step={0.05} fmt={v => `${Math.round(v * 100)}%`} onChange={v => set('fontScale', v)}/>
                <Slider label="Line spacing" value={opts.lineHeight} min={1.3} max={1.8} step={0.05} fmt={v => v.toFixed(2)} onChange={v => set('lineHeight', v)}/>
                <Slider label="Heading tracking" value={opts.headLetterSpacing} min={0} max={0.24} step={0.02} fmt={v => `${v.toFixed(2)}em`} onChange={v => set('headLetterSpacing', v)}/>
              </div>
            </div>
          )}

          {tab === 'Layout' && (
            <div>
              <Slider label="Page margins" value={opts.margin} min={24} max={64} fmt={v => `${v}px`} onChange={v => set('margin', v)}/>
              <Slider label="Section spacing" value={opts.sectionGap} min={8} max={32} fmt={v => `${v}px`} onChange={v => set('sectionGap', v)}/>
              <Slider label="Name size" value={opts.nameScale} min={0.8} max={1.5} step={0.05} fmt={v => `${Math.round(v * 100)}%`} onChange={v => set('nameScale', v)}/>
              {isSidebar && <Slider label="Sidebar width" value={opts.sidebarWidth} min={180} max={280} fmt={v => `${v}px`} onChange={v => set('sidebarWidth', v)}/>}
              <Segmented label="Heading style" value={opts.headerStyle} options={[['bar', 'Bar'], ['underline', 'Line'], ['plain', 'Plain']]} onChange={v => set('headerStyle', v)}/>
              <Segmented label="Header align" value={opts.headerAlign} options={[['left', 'Left'], ['center', 'Center']]} onChange={v => set('headerAlign', v)}/>
              <Segmented label="Bullets" value={opts.bulletStyle} options={[['dot', '•'], ['dash', '–'], ['arrow', '→'], ['none', 'None']]} onChange={v => set('bulletStyle', v)}/>
              <Segmented label="Skills" value={opts.skillStyle} options={[['pills', 'Pills'], ['comma', 'Inline'], ['list', 'List']]} onChange={v => set('skillStyle', v)}/>
              <Segmented label="Photo shape" value={opts.photoShape} options={[['circle', 'Circle'], ['rounded', 'Round'], ['square', 'Square']]} onChange={v => set('photoShape', v)}/>
              <Segmented label="Paper" value={opts.paper} options={[['letter', 'Letter'], ['a4', 'A4']]} onChange={v => set('paper', v)}/>
              <div className="stack-sm" style={{ marginTop: 4 }}>
                <BToggle label="Uppercase headings" checked={opts.uppercaseHeads} onChange={v => set('uppercaseHeads', v)}/>
                <BToggle label="Divider under headings" checked={opts.divider} onChange={v => set('divider', v)}/>
                <BToggle label="Show location" checked={opts.showLocation} onChange={v => set('showLocation', v)}/>
                <BToggle label="Show links" checked={opts.showLinks} onChange={v => set('showLinks', v)}/>
              </div>
            </div>
          )}

          {tab === 'Sections' && (
            <div>
              <div className="t-body-sm muted" style={{ marginBottom: 12 }}>Show, hide, and reorder sections.</div>
              <div className="stack-sm">
                {opts.sections.map((id, i) => (
                  <div key={id} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 10px', border: '1px solid var(--border-default)', borderRadius: 8, background: 'var(--bg-surface)', opacity: opts.hidden[id] ? 0.5 : 1 }}>
                    <div style={{ display: 'flex', flexDirection: 'column' }}>
                      <button onClick={() => moveSection(id, -1)} disabled={i === 0} style={{ border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--text-muted)', padding: 0, lineHeight: 1 }}>▲</button>
                      <button onClick={() => moveSection(id, 1)} disabled={i === opts.sections.length - 1} style={{ border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--text-muted)', padding: 0, lineHeight: 1 }}>▼</button>
                    </div>
                    <span style={{ flex: 1, fontSize: 13 }}>{SECTION_LABELS[id]}</span>
                    <button onClick={() => toggleHidden(id)} title={opts.hidden[id] ? 'Show' : 'Hide'} style={{ border: 0, background: 'transparent', cursor: 'pointer', color: opts.hidden[id] ? 'var(--text-muted)' : 'var(--accent-primary)', padding: 4 }}>
                      <Icon.eye size={16}/>
                    </button>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </aside>

      {/* Preview */}
      <main style={{ background: 'var(--bg-sunken)', overflow: 'auto', position: 'relative', padding: 32 }}>
        <div style={{ position: 'sticky', top: 0, zIndex: 5, display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <div className="t-body-sm muted">Live preview</div>
          <div style={{ display: 'flex', gap: 4, background: 'var(--bg-surface)', padding: 4, borderRadius: 999, border: '1px solid var(--border-default)' }}>
            {[50, 75, 100].map(z => (
              <button key={z} onClick={() => setZoom(z * 0.58)} style={{ padding: '4px 10px', borderRadius: 999, border: 0, background: Math.round(zoom / 0.58) === z ? 'var(--text-primary)' : 'transparent', color: Math.round(zoom / 0.58) === z ? 'var(--bg-canvas)' : 'var(--text-secondary)', cursor: 'pointer', fontFamily: 'inherit', fontSize: 11 }}>{z}%</button>
            ))}
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <div id="rr-print-area" style={{ width: 720, transform: `scale(${zoom / 100})`, transformOrigin: 'top center', transition: 'transform var(--d-base) var(--e-out)' }}>
            <BeautifyDoc data={data} opts={opts}/>
          </div>
        </div>
      </main>

      {/* Right rail */}
      <aside style={{ borderLeft: '1px solid var(--border-default)', padding: 20, background: 'var(--bg-surface)' }}>
        <Btn variant="primary" size="lg" style={{ width: '100%' }} icon={<Icon.download size={16}/>} onClick={() => window.print()}>Download PDF</Btn>
        <div className="t-body-sm muted" style={{ marginTop: 8, fontSize: 12, textAlign: 'center' }}>Choose “Save as PDF” in the print dialog.</div>

        <div className="t-mono muted" style={{ margin: '24px 0 10px', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase' }}>Filename</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 10px', background: 'var(--bg-sunken)', borderRadius: 8 }}>
          <span className="t-mono" style={{ fontSize: 11, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{fileBase}.pdf</span>
        </div>

        <Btn variant="secondary" size="sm" style={{ width: '100%', marginTop: 16 }} icon={<Icon.refresh size={14}/>} onClick={() => setOpts({ ...DEFAULT_OPTS })}>Reset style</Btn>

        <div className="t-mono muted" style={{ margin: '24px 0 10px', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase' }}>ATS readability</div>
        <div style={{ padding: 14, background: score >= 80 ? 'rgba(22,163,74,0.06)' : 'rgba(217,119,6,0.06)', border: `1px solid ${score >= 80 ? 'rgba(22,163,74,0.2)' : 'rgba(217,119,6,0.2)'}`, borderRadius: 10 }}>
          <div className="row" style={{ justifyContent: 'space-between' }}>
            <div className="t-body-sm" style={{ fontWeight: 500, color: score >= 80 ? 'var(--success)' : 'var(--warning)' }}>{score >= 80 ? 'Strong' : 'Good'} · {score}/100</div>
            <Icon.check size={16} style={{ color: score >= 80 ? 'var(--success)' : 'var(--warning)' }}/>
          </div>
          <div className="t-body-sm muted" style={{ marginTop: 6, fontSize: 12 }}>Designed PDFs read best by humans; use the Boring .doc for strict ATS.</div>
        </div>
      </aside>
    </div>
  );
}

Object.assign(window, { BeautifyScreen });
