// Overlay modals — Approval workflow + Export/Preflight.

function ModalShell({ onClose, title, subtitle, badge, width = 720, children, footer }) {
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 100,
      background: 'rgba(10, 31, 61, 0.32)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 40,
    }} onClick={onClose}>
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width, maxWidth: '100%', maxHeight: '90vh',
          background: 'var(--bg-panel)',
          border: '1px solid var(--line-strong)',
          boxShadow: '0 20px 60px rgba(10, 31, 61, 0.25)',
          display: 'flex', flexDirection: 'column',
        }}
      >
        {/* Header */}
        <div style={{
          padding: '14px 20px 12px',
          borderBottom: '1px solid var(--line)',
          background: 'var(--bg-panel-2)',
          display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between',
        }}>
          <div>
            <Row gap={10} style={{ marginBottom: 4 }}>
              <Label>{title}</Label>
              {badge}
            </Row>
            <div className="serif" style={{ fontSize: 18, color: 'var(--ink)', fontWeight: 500, letterSpacing: '-0.005em' }}>
              {subtitle}
            </div>
          </div>
          <IconBtn icon={<I.close size={14}/>} onClick={onClose}/>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflow: 'auto' }}>
          {children}
        </div>

        {footer && (
          <div style={{ padding: '12px 20px', borderTop: '1px solid var(--line)', background: 'var(--bg-panel-2)' }}>
            {footer}
          </div>
        )}
      </div>
    </div>
  );
}

// ============ APPROVAL MODAL ============
function ApprovalModal({ onClose }) {
  const stages = [
    { name: 'Designer',           who: 'A. Rao',           role: 'Design Cell · MoRD', status: 'done',    when: '14 Jul · 13:22' },
    { name: 'Peer Review',        who: 'M. Nair',          role: 'Sr. Designer',       status: 'done',    when: '14 Jul · 13:50' },
    { name: 'Reviewer',           who: 'S. Iyer',          role: 'Section Officer',    status: 'current', when: 'pending' },
    { name: 'Approving Authority',who: 'Dr. R. Krishnan',  role: 'Under Secretary',    status: 'waiting', when: '—' },
    { name: 'Publication',        who: 'System',           role: 'CPPP Portal',        status: 'waiting', when: '—' },
  ];

  const comments = [
    { who: 'S. Iyer',  role: 'Reviewer',    when: '13:50', text: 'Please right-align the date column in the Critical Dates table. Also confirm EMD figure with Accounts.', target: 'schedule' },
    { who: 'M. Nair',  role: 'Sr. Designer', when: '13:22', text: 'Devanagari body is looking clean. Consider tightening the leading by 0.5pt on the Hindi paragraph.', target: 'body' },
    { who: 'A. Rao',   role: 'Designer',    when: '11:30', text: 'Draft ready for peer review. Used the certified MoRD Tender Cover template with bilingual body.', target: null, me: true },
  ];

  return (
    <ModalShell
      onClose={onClose}
      title="Approval Workflow"
      subtitle="Tender Notice · Rural Development"
      badge={<Badge tone="warn">In Review · 2 of 5</Badge>}
      width={820}
      footer={
        <Row justify="space-between">
          <Row gap={8}>
            <Btn variant="ghost" size="sm" icon={<I.history size={12}/>}>Audit trail</Btn>
            <Btn variant="ghost" size="sm" icon={<I.copy size={12}/>}>Compare v0.6 ↔ v0.7</Btn>
          </Row>
          <Row gap={6}>
            <Btn variant="line" size="md">Request Changes</Btn>
            <Btn variant="danger" size="md">Reject</Btn>
            <Btn variant="solid" size="md" icon={<I.check size={13}/>}>Approve &amp; Advance</Btn>
          </Row>
        </Row>
      }
    >
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
        {/* Left: workflow chain */}
        <div style={{ padding: '18px 20px', borderRight: '1px solid var(--line)' }}>
          <Label style={{ marginBottom: 12 }}>Approval Chain</Label>
          <div>
            {stages.map((s, i) => {
              const done = s.status === 'done';
              const current = s.status === 'current';
              return (
                <div key={s.name} style={{ display: 'grid', gridTemplateColumns: '24px 1fr', gap: 12, position: 'relative', paddingBottom: i < stages.length - 1 ? 20 : 0 }}>
                  {/* Connector line */}
                  {i < stages.length - 1 && (
                    <div style={{ position: 'absolute', left: 11, top: 22, bottom: 0, width: 1, background: done ? 'var(--ink)' : 'var(--line-2)' }}/>
                  )}
                  {/* Dot */}
                  <div style={{
                    width: 22, height: 22,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    background: done ? 'var(--ink)' : current ? 'var(--gold)' : 'var(--bg-elevated)',
                    color: done || current ? 'var(--bg-panel)' : 'var(--ink-subtle)',
                    border: done ? '1px solid var(--ink)' : current ? '1px solid var(--gold)' : '1px solid var(--line-2)',
                    borderRadius: 2,
                    zIndex: 1,
                  }}>
                    {done ? <I.check size={11}/> : <span className="mono" style={{ fontSize: 10 }}>{i + 1}</span>}
                  </div>
                  <div>
                    <Row justify="space-between" align="baseline">
                      <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)' }}>{s.name}</div>
                      {current && <Badge tone="gold">Current</Badge>}
                    </Row>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>{s.who}</div>
                    <div className="mono" style={{ fontSize: 10, color: 'var(--ink-subtle)', marginTop: 2, letterSpacing: '0.04em' }}>
                      {s.role.toUpperCase()} · {s.when}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>

          <div style={{ marginTop: 20, padding: 12, background: 'var(--bg-elevated)', border: '1px solid var(--line)' }}>
            <Label style={{ marginBottom: 6 }}>Governance</Label>
            <div className="mono" style={{ fontSize: 10.5, color: 'var(--ink-3)', lineHeight: 1.7 }}>
              <div>policy · MoRD-DES-2024/07</div>
              <div>SLA · 48 hr per stage</div>
              <div>signature · Digital · DSC Class 3</div>
              <div>audit · Immutable · Blockchain-anchored</div>
            </div>
          </div>
        </div>

        {/* Right: comments */}
        <div style={{ padding: '18px 20px' }}>
          <Row justify="space-between" style={{ marginBottom: 12 }}>
            <Label>Comments · 3</Label>
            <Btn size="sm" variant="ghost" icon={<I.plus size={11}/>}>Reply</Btn>
          </Row>
          <Col gap={0}>
            {comments.map((c, i) => (
              <div key={i} style={{ padding: '12px 0', borderBottom: i < comments.length - 1 ? '1px solid var(--line)' : 'none' }}>
                <Row justify="space-between" align="baseline" style={{ marginBottom: 6 }}>
                  <Row gap={8}>
                    <Avatar name={c.who} tone={c.me ? 'gold' : 'ink'} size={20}/>
                    <div>
                      <div style={{ fontSize: 12, color: 'var(--ink)', fontWeight: 500 }}>{c.who}{c.me ? ' · you' : ''}</div>
                      <div className="mono" style={{ fontSize: 9.5, color: 'var(--ink-subtle)', letterSpacing: '0.06em' }}>{c.role.toUpperCase()}</div>
                    </div>
                  </Row>
                  <span className="mono" style={{ fontSize: 10, color: 'var(--ink-subtle)' }}>{c.when}</span>
                </Row>
                <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.55, marginLeft: 28 }}>
                  {c.text}
                </div>
                {c.target && (
                  <div style={{ marginLeft: 28, marginTop: 6 }}>
                    <Badge tone="neutral">
                      <I.frame size={9}/> pinned to · {c.target}
                    </Badge>
                  </div>
                )}
              </div>
            ))}
          </Col>

          <div style={{ marginTop: 16 }}>
            <textarea
              rows={3}
              placeholder="Write a comment · @mention or #pin element"
              style={{
                width: '100%',
                background: 'var(--bg-elevated)',
                border: '1px solid var(--line-2)',
                padding: '8px 10px',
                fontSize: 12, fontFamily: 'inherit',
                color: 'var(--ink)',
                resize: 'vertical',
                outline: 'none',
                lineHeight: 1.5,
                borderRadius: 2,
              }}
            />
            <Row justify="space-between" style={{ marginTop: 6 }}>
              <Row gap={4}>
                <IconBtn icon={<I.link size={12}/>} size={22}/>
                <IconBtn icon={<I.image size={12}/>} size={22}/>
              </Row>
              <Btn size="sm" variant="solid">Post Comment</Btn>
            </Row>
          </div>
        </div>
      </div>
    </ModalShell>
  );
}

// ============ EXPORT MODAL ============
function ExportModal({ onClose }) {
  const [format, setFormat] = React.useState('pdfx');
  const formats = [
    { key: 'pdfx',  name: 'PDF/X-4',      desc: 'Print-ready · CMYK · Embedded fonts',   ext: '.pdf' },
    { key: 'pdf',   name: 'PDF',          desc: 'Standard · RGB · For screen',           ext: '.pdf' },
    { key: 'svg',   name: 'SVG',          desc: 'Vector · Web-optimized',                ext: '.svg' },
    { key: 'eps',   name: 'EPS',          desc: 'Legacy · Level 3 · Print',              ext: '.eps' },
    { key: 'png',   name: 'PNG',          desc: 'Raster · Transparency · 300 dpi',       ext: '.png' },
    { key: 'jpg',   name: 'JPEG',         desc: 'Raster · Compressed · Quality 92',      ext: '.jpg' },
    { key: 'tiff',  name: 'TIFF',         desc: 'Raster · CMYK · Uncompressed',          ext: '.tif' },
    { key: 'webp',  name: 'WebP',         desc: 'Raster · Web · 40% smaller',            ext: '.webp' },
  ];

  return (
    <ModalShell
      onClose={onClose}
      title="Export · Prepress"
      subtitle="Tender Notice — Rural Development"
      badge={<Badge tone="ok">Preflight Ready</Badge>}
      width={860}
      footer={
        <Row justify="space-between">
          <Row gap={8}>
            <Btn variant="ghost" size="sm" icon={<I.settings size={12}/>}>Presets</Btn>
            <Btn variant="ghost" size="sm" icon={<I.save size={12}/>}>Save as preset</Btn>
          </Row>
          <Row gap={6}>
            <Btn variant="line" size="md" icon={<I.play size={12}/>}>Run Preflight</Btn>
            <Btn variant="solid" size="md" icon={<I.export size={13}/>}>Export · 4 pages</Btn>
          </Row>
        </Row>
      }
    >
      <div style={{ display: 'grid', gridTemplateColumns: '260px 1fr' }}>
        {/* Left: format list */}
        <div style={{ borderRight: '1px solid var(--line)', padding: '12px 0' }}>
          <Label style={{ padding: '0 16px 8px' }}>Formats</Label>
          {formats.map((f) => {
            const active = format === f.key;
            return (
              <button
                key={f.key}
                onClick={() => setFormat(f.key)}
                style={{
                  display: 'block',
                  width: '100%',
                  textAlign: 'left',
                  padding: '10px 16px',
                  background: active ? 'var(--bg-elevated)' : 'transparent',
                  borderLeft: active ? '2px solid var(--gold)' : '2px solid transparent',
                  cursor: 'pointer',
                }}
              >
                <Row justify="space-between" align="baseline">
                  <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)' }}>{f.name}</span>
                  <span className="mono" style={{ fontSize: 10, color: 'var(--ink-subtle)' }}>{f.ext}</span>
                </Row>
                <div style={{ fontSize: 11, color: 'var(--ink-muted)', marginTop: 2 }}>{f.desc}</div>
              </button>
            );
          })}
        </div>

        {/* Right: options + preflight */}
        <div style={{ padding: '18px 20px' }}>
          <Label style={{ marginBottom: 10 }}>Export Options · PDF/X-4</Label>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 20 }}>
            <ExportOpt label="Color Space"    value="CMYK · Fogra 39"/>
            <ExportOpt label="Resolution"     value="300 dpi"/>
            <ExportOpt label="Bleed"          value="3 mm all sides"/>
            <ExportOpt label="Crop Marks"     value="On · 0.25 pt"/>
            <ExportOpt label="Compression"    value="Lossless"/>
            <ExportOpt label="Font Embedding" value="Subset · Full"/>
            <ExportOpt label="Transparency"   value="Flatten · High"/>
            <ExportOpt label="Pages"          value="1–4 · All"/>
          </div>

          <div style={{ padding: 12, background: 'var(--bg-panel-2)', border: '1px solid var(--line)', marginBottom: 16 }}>
            <Row justify="space-between" style={{ marginBottom: 8 }}>
              <Label>Preflight Report</Label>
              <span className="mono" style={{ fontSize: 10, color: 'var(--ink-subtle)' }}>ran 14:32:16 IST</span>
            </Row>
            <Col gap={4}>
              <PreflightRow state="ok"   label="Color space uniformly CMYK"        detail="4 pages · verified"/>
              <PreflightRow state="ok"   label="All fonts embedded (subset)"      detail="Fraunces · Noto Sans Dev · Inter · JB Mono"/>
              <PreflightRow state="ok"   label="Bleed applied · 3 mm"              detail="All artboards"/>
              <PreflightRow state="ok"   label="Devanagari shaping OpenType"       detail="dlig · calt · ss01"/>
              <PreflightRow state="warn" label="Image resolution below 300 dpi"   detail="1 image · 254 dpi · Page 03"/>
              <PreflightRow state="ok"   label="Ink coverage below 300%"           detail="Max 268% · Page 02"/>
              <PreflightRow state="ok"   label="No missing linked assets"          detail="12 links · all resolved"/>
              <PreflightRow state="ok"   label="Copyright · similarity check"      detail="No matches · database v2026.07"/>
            </Col>
          </div>

          <Row justify="space-between" style={{ fontSize: 11.5, color: 'var(--ink-muted)' }}>
            <span>Estimated output · <span className="mono" style={{ color: 'var(--ink-3)' }}>~ 2.4 MB · 4 pages</span></span>
            <span>Destination · <span className="mono" style={{ color: 'var(--ink-3)' }}>/exports/mord/tenders/</span></span>
          </Row>
        </div>
      </div>
    </ModalShell>
  );
}

function ExportOpt({ label, value }) {
  return (
    <div style={{ borderTop: '1px solid var(--line)', paddingTop: 8 }}>
      <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-subtle)' }}>{label}</div>
      <Row justify="space-between" style={{ marginTop: 3 }}>
        <span style={{ fontSize: 12.5, color: 'var(--ink)' }}>{value}</span>
        <button style={{ fontSize: 11, color: 'var(--gold)', background: 'none', border: 'none', cursor: 'pointer' }}>Edit</button>
      </Row>
    </div>
  );
}

function PreflightRow({ state, label, detail }) {
  const map = {
    ok:   { icon: <I.ok size={12}/>,   color: 'var(--status-ok)' },
    warn: { icon: <I.warn size={12}/>, color: 'var(--status-warn)' },
    err:  { icon: <I.warn size={12}/>, color: 'var(--status-err)' },
  }[state];
  return (
    <Row justify="space-between" style={{ fontSize: 11.5, padding: '3px 0' }}>
      <Row gap={8}>
        <span style={{ color: map.color, display: 'inline-flex' }}>{map.icon}</span>
        <span style={{ color: 'var(--ink-2)' }}>{label}</span>
      </Row>
      <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-subtle)' }}>{detail}</span>
    </Row>
  );
}

Object.assign(window, { ApprovalModal, ExportModal });
