// sv-step-review.jsx — Step 4: Review & submit

const { useState: useRevSt } = React;

function SummaryRow({ label, value, muted }) {
  return (
    <div style={{ display: 'flex', gap: 12, padding: '8px 0', borderBottom: '1px solid var(--sv-line-1)' }}>
      <div style={{ width: 148, fontSize: 12, fontWeight: 600, color: 'var(--sv-fg-3)', flexShrink: 0, paddingTop: 1, letterSpacing: '0.02em' }}>{label}</div>
      <div style={{ fontSize: 14, color: (muted || !value) ? 'var(--sv-fg-4)' : 'var(--sv-fg-1)', lineHeight: 1.5 }}>{value || 'Not provided'}</div>
    </div>
  );
}

function ReviewStep({ onBack }) {
  const { data, updateAcks, submitForm } = useFormContext();
  const [submitted, useSubmittedSt] = useRevSt(false);
  const [finalScore, setFinalScore] = useRevSt(null);

  const score = calculateReadinessScore(data);

  const handleSubmit = () => {
    const s = calculateReadinessScore(data);
    submitForm();
    setFinalScore(s);
    useSubmittedSt(true);
  };

  if (submitted) {
    const fs = finalScore || 0;
    const status = fs >= 8 ? 'Ready for setup' : fs >= 5 ? 'Waiting on SOPs' : 'New submission';
    const tone = fs >= 8 ? 'live' : fs >= 5 ? 'warn' : 'neutral';
    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '56px 0 80px', gap: 28, textAlign: 'center' }}>
        <div style={{ width: 60, height: 60, borderRadius: 9999, background: 'var(--sv-ok-tint)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="check" size={28} color="var(--sv-ok)" />
        </div>
        <div>
          <h2 style={{ fontSize: 26, fontWeight: 700, letterSpacing: '-0.02em', margin: '0 0 8px' }}>Let's get your pilot rolling</h2>
          <p style={{ fontSize: 15, color: 'var(--sv-fg-2)', maxWidth: 460, margin: '0 auto', lineHeight: 1.6 }}>Your request is in and our team is already reviewing it. The fastest way to kick things off is to grab a time below for a quick onboarding call — we'll walk through your setup, answer questions, and map out exactly what your pilot will look like.</p>
        </div>
        <div style={{ display: 'flex', gap: 20, padding: '16px 28px', background: 'var(--sv-bg-elev-1)', border: '1px solid var(--sv-line-1)', borderRadius: 'var(--sv-r-lg)', alignItems: 'center' }}>
          <div style={{ textAlign: 'left' }}>
            <div style={{ fontSize: 11, color: 'var(--sv-fg-3)', marginBottom: 4, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase' }}>Readiness score</div>
            <ScoreBadge score={fs} />
          </div>
          <div style={{ width: 1, height: 36, background: 'var(--sv-line-1)' }} />
          <div style={{ textAlign: 'left' }}>
            <div style={{ fontSize: 11, color: 'var(--sv-fg-3)', marginBottom: 4, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase' }}>Status</div>
            <Pill tone={tone} dot>{status}</Pill>
          </div>
        </div>
        <div style={{ width: '100%', maxWidth: 640, textAlign: 'left' }}>
          <h3 style={{ fontSize: 18, fontWeight: 700, letterSpacing: '-0.01em', margin: '0 0 4px', textAlign: 'center' }}>Grab a time for your onboarding call</h3>
          <p style={{ fontSize: 13, color: 'var(--sv-fg-3)', margin: '0 0 14px', textAlign: 'center' }}>Just 30 minutes over Google Meet — no prep needed, we'll handle the rest.</p>
          <div style={{ borderRadius: 'var(--sv-r-lg)', overflow: 'hidden', border: '1px solid var(--sv-line-1)' }}>
            <iframe src="https://calendar.google.com/calendar/appointments/schedules/AcZssZ34ba7FkreIaxGyk4NcLSwfqMm5Mdx95roRUkUN8jV2bu8NDuDHT7h_QkhqTTAhSGE5h7sUTiu-?gv=true" style={{ border: 0, width: '100%', height: 600, display: 'block' }} frameBorder="0" title="Book your onboarding call" />
          </div>
        </div>
      </div>
    );
  }

  const scoreStatus = score >= 8 ? 'All key information captured.' : score >= 5 ? 'A few more details will help scope your pilot.' : 'Add more details to improve pilot readiness.';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>

      {/* Score bar */}
      <div style={{ padding: '18px 22px', background: 'var(--sv-bg-elev-1)', border: '1px solid var(--sv-line-1)', borderRadius: 'var(--sv-r-xl)', display: 'flex', alignItems: 'center', gap: 20 }}>
        <div style={{ flexShrink: 0 }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.07em', textTransform: 'uppercase', color: 'var(--sv-fg-3)', marginBottom: 5 }}>Readiness score</div>
          <ScoreBadge score={score} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ height: 6, background: 'var(--sv-bg-sunken)', borderRadius: 9999, overflow: 'hidden', marginBottom: 6 }}>
            <div style={{ height: '100%', width: `${score * 10}%`, background: score >= 8 ? 'var(--sv-ok)' : score >= 5 ? 'var(--sv-warn)' : 'var(--sv-accent)', borderRadius: 9999, transition: 'width 500ms var(--sv-ease-soft)' }} />
          </div>
          <div style={{ fontSize: 12, color: 'var(--sv-fg-3)' }}>{scoreStatus}</div>
        </div>
      </div>

      {/* Summary — Setup */}
      <Card>
        <Section title="Company & facility">
          <SummaryRow label="Company" value={data.companyName} />
          <SummaryRow label="Facility" value={[data.facilityName, data.facilityAddress].filter(Boolean).join(' · ')} />
          <SummaryRow label="Contact" value={[data.contactName, data.contactTitle, data.contactEmail].filter(Boolean).join(' · ')} />
          <SummaryRow label="Profile" value={[data.facilityType, data.facilitySize, data.employees && `${data.employees} employees`].filter(Boolean).join(' · ')} />
          <SummaryRow label="Schedule" value={`${data.operatingDays} · ${data.operatingHours} · ${data.shiftsPerDay}`} />
          {data.bottleneck && <SummaryRow label="Bottleneck" value={data.bottleneck} />}
        </Section>
      </Card>

      {/* Summary — Scope */}
      <Card>
        <Section title="Scope">
          <SummaryRow label="Zones" value={data.zones.map(z => z.name || 'Unnamed zone').join(', ')} />
          <SummaryRow label="Workflows" value={(data.workflows || []).join(', ')} />
          <SummaryRow label="Goals" value={(data.goals || []).join(', ')} />
          <SummaryRow label="Report frequency" value={data.reportFrequency} />
          {data.successLookLike && <SummaryRow label="Success definition" value={data.successLookLike} />}
          {(() => {
            const count = Object.values(data.zoneSOPs || {}).reduce((a, f) => a + (Array.isArray(f) ? f.length : 0), 0);
            return count > 0 ? <SummaryRow label="SOPs attached" value={`${count} file${count !== 1 ? 's' : ''}`} /> : null;
          })()}
        </Section>
      </Card>

      {/* Summary — Access */}
      <Card>
        <Section title="Access">
          <SummaryRow label="VMS provider" value={data.vmsProvider} />
          {data.loginUrl && <SummaryRow label="Login URL" value={data.loginUrl} />}
          <SummaryRow label="Cameras installed" value={data.hasCameras} />
          {data.internalSecurityReqs && <SummaryRow label="Security requirements" value={data.internalSecurityReqs} />}
        </Section>
      </Card>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingBottom: 8 }}>
        <Button variant="secondary" icon="arrow-left" onClick={onBack}>Back</Button>
        <Button onClick={handleSubmit} icon="send">Submit pilot request</Button>
      </div>
    </div>
  );
}

Object.assign(window, { ReviewStep, SummaryRow });
