// Multi-step New Request flow.
// Steps: 1 Category  ·  2 Details  ·  3 Attachments  ·  4 Priority & SLA  ·  5 Review

function NewRequestModal({ pal, onClose }) {
  const t = useTweaks();
  const jm = window.JOY_MOVE;
  const plan = jm.plans[t.tier];

  const [step, setStep] = React.useState(1);
  const [data, setData] = React.useState({
    category: null, title: '', body: '', attachments: [], priority: 'Normal', rush: false,
  });
  const [submitted, setSubmitted] = React.useState(false);

  const update = (next) => setData(d => ({ ...d, ...next }));

  const canNext = {
    1: !!data.category,
    2: data.title.trim().length > 3 && data.body.trim().length > 5,
    3: true,
    4: !!data.priority,
    5: true,
  }[step];

  const [submitting, setSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);
  const [newId, setNewId] = React.useState(null);

  const submit = async () => {
    setSubmitting(true);
    setSubmitError(null);
    try {
      const slug = window.getPortalParams().slug;
      const res = await window.Portal.submitRequest(slug, {
        category: data.category,
        title: data.title,
        body: data.body,
        attachments: data.attachments,
        priority: data.priority,
        rush: data.rush,
      });
      setNewId(res.requestId || 'JM-NEW');
      setSubmitted(true);
    } catch (e) {
      setSubmitError(e.message || 'Could not send — please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  const steps = [
    { n: 1, label: 'Category' },
    { n: 2, label: 'Details' },
    { n: 3, label: 'Files' },
    { n: 4, label: 'Priority' },
    { n: 5, label: 'Review' },
  ];

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 5000,
      background: 'rgba(11,17,32,0.7)', backdropFilter: 'blur(6px)',
      display: 'grid', placeItems: 'center', padding: 20,
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxWidth: 720, maxHeight: '90vh', overflow: 'hidden',
        background: pal.card, border: `1px solid ${pal.border}`, borderRadius: 16,
        boxShadow: '0 40px 80px rgba(0,0,0,0.5)',
        display: 'flex', flexDirection: 'column',
      }}>
        {submitted ? (
          <SubmittedScreen pal={pal} data={data} onClose={onClose} requestId={newId} />
        ) : (
          <>
            <ModalHeader pal={pal} step={step} steps={steps} onClose={onClose} />
            <div style={{ padding: '28px 36px', overflow: 'auto', flex: 1 }}>
              {step === 1 && <Step1Category pal={pal} data={data} update={update} />}
              {step === 2 && <Step2Details pal={pal} data={data} update={update} />}
              {step === 3 && <Step3Attach pal={pal} data={data} update={update} />}
              {step === 4 && <Step4Priority pal={pal} data={data} update={update} plan={plan} />}
              {step === 5 && <Step5Review pal={pal} data={data} plan={plan} />}
            </div>
            <div style={{
              padding: '16px 36px', borderTop: `1px solid ${pal.border}`,
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              background: pal.warm,
            }}>
              {step > 1 ? <BtnGhost pal={pal} onClick={() => setStep(s => s - 1)}>← Back</BtnGhost> : <span />}
              <div style={{ fontSize: 12, color: pal.muted }}>
                {submitError ? <span style={{ color: pal.warn }}>{submitError}</span> : `Step ${step} of ${steps.length}`}
              </div>
              {step < 5 ? (
                <BtnPrimary pal={pal} disabled={!canNext} onClick={() => setStep(s => s + 1)}>Continue →</BtnPrimary>
              ) : (
                <BtnPrimary pal={pal} disabled={submitting} onClick={submit}>{submitting ? 'Sending…' : 'Submit request'}</BtnPrimary>
              )}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function ModalHeader({ pal, step, steps, onClose }) {
  return (
    <div style={{ padding: '20px 36px', borderBottom: `1px solid ${pal.border}` }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
        <div>
          <Kicker pal={pal}>New request</Kicker>
          <div style={{ fontFamily: "'Playfair Display', serif", fontSize: 22, fontWeight: 700, color: pal.navy, letterSpacing: '-0.01em' }}>
            Tell us what you need
          </div>
        </div>
        <button onClick={onClose} style={{ border: 'none', background: 'transparent', color: pal.muted, cursor: 'pointer', fontSize: 22, padding: 4 }}>×</button>
      </div>
      {/* Step dots */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        {steps.map((s, i) => (
          <React.Fragment key={s.n}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 8,
              color: s.n === step ? pal.accent : s.n < step ? pal.textStrong : pal.muted,
            }}>
              <div style={{
                width: 22, height: 22, borderRadius: '50%',
                background: s.n === step ? pal.accent : s.n < step ? pal.warm : 'transparent',
                color: s.n === step ? pal.onAccent : s.n < step ? pal.textStrong : pal.muted,
                border: s.n < step ? `1px solid ${pal.border}` : s.n === step ? 'none' : `1px solid ${pal.border}`,
                display: 'grid', placeItems: 'center',
                fontSize: 11, fontWeight: 700,
              }}>{s.n < step ? '✓' : s.n}</div>
              <span style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.04em' }}>{s.label}</span>
            </div>
            {i < steps.length - 1 && <div style={{ flex: 1, height: 1, background: s.n < step ? pal.accent : pal.border, opacity: s.n < step ? 0.5 : 1 }} />}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

function Step1Category({ pal, data, update }) {
  const cats = window.JOY_MOVE.requestCategories;
  return (
    <div>
      <div style={{ fontSize: 15, color: pal.textStrong, fontWeight: 500, marginBottom: 6 }}>What kind of request?</div>
      <div style={{ fontSize: 13, color: pal.muted, marginBottom: 20, fontWeight: 300 }}>Pick the closest match — helps us route and estimate accurately.</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {cats.map(c => {
          const active = data.category === c.id;
          return (
            <div key={c.id} onClick={() => update({ category: c.id })} style={{
              padding: 16, borderRadius: 12, cursor: 'pointer',
              background: active ? pal.warm : 'transparent',
              border: `1px solid ${active ? pal.accent : pal.border}`,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
                <span style={{ color: pal.accent, fontSize: 16, fontWeight: 700, width: 20 }}>{c.icon}</span>
                <span style={{ fontSize: 14, fontWeight: 600, color: pal.textStrong }}>{c.label}</span>
              </div>
              <div style={{ fontSize: 12, color: pal.muted, marginBottom: 6, paddingLeft: 30 }}>{c.sub}</div>
              <div style={{ fontSize: 11, color: pal.accent, fontWeight: 600, paddingLeft: 30, fontFamily: "'JetBrains Mono', monospace" }}>{c.est}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function Step2Details({ pal, data, update }) {
  return (
    <div>
      <div style={{ fontSize: 15, color: pal.textStrong, fontWeight: 500, marginBottom: 6 }}>Give us the details</div>
      <div style={{ fontSize: 13, color: pal.muted, marginBottom: 20, fontWeight: 300 }}>The more specific, the faster we can get this done without follow-ups.</div>
      <div style={{ marginBottom: 18 }}>
        <label style={{ display: 'block', fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: pal.muted, marginBottom: 8 }}>Title</label>
        <Input pal={pal} placeholder="e.g. Swap homepage hero image" value={data.title} onChange={e => update({ title: e.target.value })} />
      </div>
      <div>
        <label style={{ display: 'block', fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: pal.muted, marginBottom: 8 }}>What needs to happen?</label>
        <Textarea pal={pal}
          placeholder="Where on the site, what should change, and any constraints (deadline, brand guidelines, etc)."
          value={data.body}
          onChange={e => update({ body: e.target.value })}
          style={{ minHeight: 140 }}
        />
        <div style={{ fontSize: 11, color: pal.muted, marginTop: 6, fontStyle: 'italic' }}>Tip: a link to the exact page or a screenshot saves us both time.</div>
      </div>
    </div>
  );
}

function Step3Attach({ pal, data, update }) {
  const demo = ['screenshot.png', 'new-copy.docx'];
  return (
    <div>
      <div style={{ fontSize: 15, color: pal.textStrong, fontWeight: 500, marginBottom: 6 }}>Attach anything relevant</div>
      <div style={{ fontSize: 13, color: pal.muted, marginBottom: 20, fontWeight: 300 }}>Images, PDFs, brand assets, screenshots — optional but helpful.</div>
      <div style={{
        padding: 36, borderRadius: 14,
        border: `2px dashed ${pal.border}`, background: pal.warm,
        textAlign: 'center', cursor: 'pointer',
      }}>
        <div style={{ fontSize: 28, color: pal.accent, marginBottom: 10 }}>⎙</div>
        <div style={{ fontSize: 14, color: pal.textStrong, fontWeight: 600, marginBottom: 4 }}>Drop files here or click to browse</div>
        <div style={{ fontSize: 12, color: pal.muted }}>PNG, JPG, PDF, DOC, SVG · up to 25 MB each</div>
      </div>
      {data.attachments.length > 0 && (
        <div style={{ marginTop: 18, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {data.attachments.map(a => (
            <div key={a} style={{ padding: '8px 12px', background: pal.warm, border: `1px solid ${pal.border}`, borderRadius: 8, fontSize: 12, color: pal.textStrong }}>⎙ {a}</div>
          ))}
        </div>
      )}
      <div style={{ marginTop: 20, display: 'flex', gap: 10 }}>
        <BtnGhost pal={pal} onClick={() => update({ attachments: demo })}>Use demo files</BtnGhost>
        {data.attachments.length > 0 && <BtnText pal={pal} onClick={() => update({ attachments: [] })}>Clear</BtnText>}
      </div>
    </div>
  );
}

function Step4Priority({ pal, data, update, plan }) {
  const priorities = [
    { v: 'Low', label: 'Low', sub: 'Whenever you get to it' },
    { v: 'Normal', label: 'Normal', sub: `${plan.responseSLA}` },
    { v: 'High', label: 'High', sub: 'Actively impacts my visitors' },
  ];
  return (
    <div>
      <div style={{ fontSize: 15, color: pal.textStrong, fontWeight: 500, marginBottom: 6 }}>How urgent is this?</div>
      <div style={{ fontSize: 13, color: pal.muted, marginBottom: 20, fontWeight: 300 }}>Your plan includes a {plan.responseSLA.toLowerCase()}. We'll use priority to sort the queue — not to change SLAs.</div>
      <div style={{ display: 'grid', gap: 10 }}>
        {priorities.map(p => {
          const active = data.priority === p.v;
          return (
            <div key={p.v} onClick={() => update({ priority: p.v })} style={{
              padding: '14px 18px', borderRadius: 12, cursor: 'pointer',
              background: active ? pal.warm : 'transparent',
              border: `1px solid ${active ? pal.accent : pal.border}`,
              display: 'flex', alignItems: 'center', gap: 14,
            }}>
              <div style={{
                width: 20, height: 20, borderRadius: '50%',
                border: `2px solid ${active ? pal.accent : pal.border}`,
                background: active ? pal.accent : 'transparent',
                flexShrink: 0,
              }} />
              <div>
                <div style={{ fontSize: 14, fontWeight: 600, color: pal.textStrong }}>{p.label}</div>
                <div style={{ fontSize: 12, color: pal.muted, marginTop: 2 }}>{p.sub}</div>
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ marginTop: 18, padding: '14px 16px', background: pal.warm, border: `1px solid ${pal.border}`, borderRadius: 10, display: 'flex', alignItems: 'center', gap: 12 }}>
        <input type="checkbox" checked={data.rush} onChange={e => update({ rush: e.target.checked })} style={{ accentColor: pal.accent, width: 16, height: 16 }} />
        <div style={{ fontSize: 13, color: pal.textStrong }}>
          Mark as <strong>site-down emergency</strong>
          <div style={{ fontSize: 11, color: pal.muted, marginTop: 2 }}>Use only if the site is offline or broken for visitors. We'll page within 1 hour.</div>
        </div>
      </div>
    </div>
  );
}

function Step5Review({ pal, data, plan }) {
  const cat = window.JOY_MOVE.requestCategories.find(c => c.id === data.category);
  return (
    <div>
      <div style={{ fontSize: 15, color: pal.textStrong, fontWeight: 500, marginBottom: 6 }}>Review & submit</div>
      <div style={{ fontSize: 13, color: pal.muted, marginBottom: 20, fontWeight: 300 }}>Everything look right?</div>
      <Card pal={pal} padding={22} style={{ background: pal.warm }}>
        <div style={{ display: 'grid', gap: 16 }}>
          <KV pal={pal} label="Category" v={cat?.label} />
          <KV pal={pal} label="Title" v={data.title || '—'} />
          <div>
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: pal.muted, marginBottom: 4 }}>Description</div>
            <div style={{ fontSize: 13, color: pal.textStrong, lineHeight: 1.6 }}>{data.body || '—'}</div>
          </div>
          <KV pal={pal} label="Attachments" v={data.attachments.length ? data.attachments.join(', ') : 'None'} />
          <KV pal={pal} label="Priority" v={`${data.priority}${data.rush ? ' · Emergency' : ''}`} />
          <KV pal={pal} label="Estimated turnaround" v={data.rush ? 'Within 1 hour' : plan.responseSLA} />
        </div>
      </Card>
      <div style={{ marginTop: 18, fontSize: 12, color: pal.muted, lineHeight: 1.55, fontStyle: 'italic' }}>
        We'll confirm scope and estimated hours before billing anything outside your {plan.hoursIncluded}-hour monthly allotment.
      </div>
    </div>
  );
}

function SubmittedScreen({ pal, data, onClose, requestId }) {
  const rgb = hexToRgb(pal.accent);
  return (
    <div style={{ padding: '60px 40px', textAlign: 'center' }}>
      <div style={{
        width: 72, height: 72, borderRadius: '50%', margin: '0 auto 22px',
        background: `rgba(${rgb},0.14)`, color: pal.accent,
        display: 'grid', placeItems: 'center', fontSize: 32, fontWeight: 700,
      }}>✓</div>
      <Display pal={pal} size={28} style={{ marginBottom: 10 }}>Request received.</Display>
      <div style={{ fontSize: 14, color: pal.muted, maxWidth: 440, margin: '0 auto 28px', lineHeight: 1.6, fontWeight: 300 }}>
        Filed as <strong style={{ color: pal.textStrong, fontFamily: "'JetBrains Mono', monospace" }}>{requestId || 'JM-NEW'}</strong>. We'll confirm scope and estimate within your SLA window.
      </div>
      <BtnPrimary pal={pal} onClick={onClose}>Back to portal</BtnPrimary>
    </div>
  );
}

window.NewRequestModal = NewRequestModal;
