/* S7 — order status / confirmation. Reachable states with a review switcher. */
const DSs = window.SparkleClassicDesignSystem_7a1470;

const ORDER_ID = 'SPK-4821';

/* honest 3-node tracker (no fake %) */
function Tracker({ stage }) {
  const { Icon } = DSs;
  // stage: 0 received, 1 art, 2 ready
  const nodes = [
    { t: 'Received', d: 'We\u2019ve got your photo and details.' },
    { t: 'Art in progress', d: 'A real person is making your sprite by hand.' },
    { t: 'Ready', d: 'Your private play link is live.' },
  ];
  return (
    <div style={{ display: 'grid', gap: 0 }}>
      {nodes.map((n, i) => {
        const done = i < stage, current = i === stage;
        const bg = done ? 'var(--success)' : current ? 'var(--action)' : 'var(--cream-surface)';
        const fg = (done || current) ? 'var(--cream)' : 'var(--plum-accent)';
        return (
          <div key={n.t} style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flex: '0 0 auto' }}>
              <span style={{ width: 34, height: 34, display: 'flex', alignItems: 'center', justifyContent: 'center', background: bg, color: fg, boxShadow: 'var(--ofx-edges)', fontSize: 14 }}>
                {done ? <Icon name="check" size={16} /> : current ? <Icon name="loader" size={16} /> : <span style={{ fontFamily: 'var(--font-pixel)', fontSize: 9 }}>{i + 1}</span>}
              </span>
              {i < nodes.length - 1 && <span style={{ width: 3, height: 26, background: done ? 'var(--success)' : 'var(--border-soft)' }} />}
            </div>
            <div style={{ paddingBottom: i < nodes.length - 1 ? 18 : 0, flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                <strong style={{ fontSize: 16, color: 'var(--plum-ink)', whiteSpace: 'nowrap' }}>{n.t}</strong>
                {current && <span style={{ fontFamily: 'var(--font-pixel)', fontSize: 7, color: 'var(--cream)', background: 'var(--action)', padding: '3px 5px' }}>NOW</span>}
                {done && <span style={{ fontFamily: 'var(--font-pixel)', fontSize: 7, color: 'var(--cream)', background: 'var(--success)', padding: '3px 5px' }}>DONE</span>}
              </div>
              <p className="spk-muted" style={{ margin: '2px 0 0', fontSize: 13.5 }}>{n.d}</p>
            </div>
          </div>
        );
      })}
    </div>
  );
}

/* while-you-wait actions */
function WaitActions({ onWatchDemo, onStart }) {
  const { Card, Icon } = DSs;
  const rows = [
    { icon: 'play', t: 'Watch the demo', d: 'See the game while you wait.', on: onWatchDemo },
    { icon: 'heart', t: 'Follow us', d: 'New pet heroes every week.', on: () => {} },
    { icon: 'plus', t: 'Refer a friend', d: 'Make their pet next.', on: onStart },
  ];
  return (
    <div style={{ display: 'grid', gap: 10 }}>
      {rows.map((r) => (
        <button key={r.t} onClick={r.on} style={{ textAlign: 'left', background: 'none', border: 'none', padding: 0, cursor: 'pointer' }}>
          <Card surface="card" padding="sm" interactive style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
            <span style={{ width: 40, height: 40, flex: '0 0 auto', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--cream)', color: 'var(--plum-ink)', boxShadow: 'var(--ofx-edges)', fontSize: 18 }}><Icon name={r.icon} /></span>
            <div style={{ flex: 1 }}>
              <strong style={{ fontSize: 15, color: 'var(--plum-ink)' }}>{r.t}</strong>
              <div className="spk-muted" style={{ fontSize: 13 }}>{r.d}</div>
            </div>
            <Icon name="chevron-right" />
          </Card>
        </button>
      ))}
    </div>
  );
}

function StatusScreen({ data, onHome, onStart, onWatchDemo, onFixPhoto }) {
  const { Button, Card, Badge, Sparkle, Icon, Dialog, Toast, Input, Textarea } = DSs;
  const [state, setState] = React.useState('received');
  const [refundOpen, setRefundOpen] = React.useState(false);
  const [refundForm, setRefundForm] = React.useState({ email: (data && data.email) || '', reason: '' });
  const [refundState, setRefundState] = React.useState('idle'); // idle | sending | sent
  const [helpOpen, setHelpOpen] = React.useState(false);
  const [toast, setToast] = React.useState(null);
  const [order, setOrder] = React.useState(null);
  const [wallState, setWallState] = React.useState('idle'); // idle|pending
  const [wallChecked, setWallChecked] = React.useState(false);
  const [wallTermsOpen, setWallTermsOpen] = React.useState(false);
  const [wallTerms, setWallTerms] = React.useState(null);
  const [wallBusy, setWallBusy] = React.useState(false);
  const orderId = (typeof location !== 'undefined' ? new URLSearchParams(location.search) : new URLSearchParams()).get('order');

  React.useEffect(() => {
    if (!orderId) return;
    let timer = null;
    const map = { draft: 'received', paid: 'received', in_progress: 'art', ready: 'ready', needs_info: 'photo', refunded: 'refunded' };
    const load = () => fetch('/api/order-status?id=' + encodeURIComponent(orderId))
      .then((r) => (r.ok ? r.json() : null))
      .then((o) => {
        if (!o) return;
        setOrder(o);
        const s = map[o.status] || 'received';
        setState(s);
        if ((s === 'ready' || s === 'refunded') && timer) { clearInterval(timer); timer = null; }
      })
      .catch(() => {});
    load();
    timer = setInterval(load, 20000); // live-update the open page while waiting
    return () => { if (timer) clearInterval(timer); };
  }, [orderId]);

  React.useEffect(() => {
    fetch('/api/wall?terms=1').then((r) => (r.ok ? r.json() : null)).then((t) => { if (t) setWallTerms(t); }).catch(() => {});
  }, []);

  const WALL = (wallTerms && wallTerms.name) || 'Pixel Pals';
  const submitWall = async () => {
    if (!wallChecked) return;
    if (!orderId) { setWallState('pending'); return; } // preview mode: no real order
    setWallBusy(true);
    try {
      const r = await fetch('/api/wall', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'consent', orderId }) });
      if (!r.ok) throw new Error('failed');
      setWallState('pending');
    } catch (e) {
      setToast({ tone: 'danger', title: 'Hmm', msg: 'Could not submit right now. Please try again.' });
      setTimeout(() => setToast(null), 2600);
    }
    setWallBusy(false);
  };

  const pet = (order && order.petName) || data.petName || 'Buttercup';
  const slug = (order && order.slug) || (window.slugify && window.slugify(pet)) || 'buttercup';
  const orderRef = (order && order.id) || orderId || ORDER_ID;
  const [refundErr, setRefundErr] = React.useState(null);

  // Refund requests are REVIEWED, not self-served: this files a support ticket
  // (team gets it, customer gets a confirmation). A real refund only happens when
  // an admin issues it via /api/refund, which flips the order to status 'refunded'.
  const submitRefund = async () => {
    if (refundState === 'sending') return;
    const email = (refundForm.email || '').trim();
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) { setRefundErr('Please add your email so we can reply.'); return; }
    setRefundState('sending'); setRefundErr(null);
    try {
      const r = await fetch('/api/wall', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'support', name: (data && data.customerName) || '', email,
          subject: `Refund request — order #${orderRef || ''}`,
          message: `Refund request from the order page.\n\nReason: ${(refundForm.reason || '').trim() || '(none given)'}\n\nOrder: #${orderRef || ''} (id ${orderId || ''})`,
        }),
      });
      const out = await r.json().catch(() => ({}));
      if (!r.ok || !out.ok) throw new Error(out.error || 'Could not send. Please try again, or email us.');
      setRefundState('sent');
    } catch (e) { setRefundErr((e && e.message) || 'Could not send. Please try again.'); setRefundState('idle'); }
  };

  const states = [
    ['received', 'Received'], ['art', 'Art in progress'], ['ready', 'Ready'],
    ['photo', 'Photo issue'], ['refunded', 'Refunded'],
  ];

  const copyLink = () => {
    setToast({ tone: 'success', title: 'Link copied', msg: 'Send it to anyone — they can play in a browser.' });
    setTimeout(() => setToast(null), 2600);
  };

  return (
    <div style={{ padding: '14px 18px 30px', position: 'relative' }}>
      {/* review-only state switcher */}
      <div style={{ border: '2px dashed var(--plum-accent)', padding: '8px 10px 10px', marginBottom: 18, display: orderId ? 'none' : 'block' }}>
        <div style={{ fontFamily: 'var(--font-pixel)', fontSize: 7, color: 'var(--plum-accent)', marginBottom: 7 }}>PREVIEW STATE · FOR REVIEW</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {states.map(([k, label]) => (
            <button key={k} onClick={() => setState(k)} aria-pressed={state === k} style={{
              fontFamily: 'var(--font-body)', fontWeight: 800, fontSize: 12, cursor: 'pointer',
              padding: '5px 10px', boxShadow: 'var(--ofx-edges)', whiteSpace: 'nowrap',
              background: state === k ? 'var(--action)' : 'var(--cream-surface)',
              color: state === k ? 'var(--cream)' : 'var(--plum-ink)', border: 0,
            }}>{label}</button>
          ))}
        </div>
      </div>

      {/* ---------- RECEIVED / ART ---------- */}
      {(state === 'received' || state === 'art') && (
        <div>
          <div style={{ textAlign: 'center', marginBottom: 18 }}>
            <Sparkle size={36} twinkle />
            <h1 className="spk-h2" style={{ fontSize: 25, margin: '6px 0 6px' }}>Yes! {pet}&rsquo;s game is being made.</h1>
            <p className="spk-muted" style={{ fontSize: 14, margin: 0 }}>
              Order <strong style={{ color: 'var(--plum-ink)' }}>#{orderRef}</strong>
            </p>
          </div>
          <Card surface="card" padding="lg" style={{ marginBottom: 16 }}>
            <Tracker stage={state === 'received' ? 0 : 1} />
          </Card>
          <Card surface="pink" padding="md" style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 20 }}>
            <span style={{ color: 'var(--plum-ink)', fontSize: 20, flex: '0 0 auto' }}><Icon name="mail" /></span>
            <p style={{ margin: 0, fontSize: 14, color: 'var(--plum-ink)', fontWeight: 600 }}>
              We&rsquo;ll email you within 24 hours with your private play link.
            </p>
          </Card>
          <h3 className="spk-h4" style={{ fontSize: 16, margin: '0 0 10px' }}>While you wait</h3>
          <WaitActions onWatchDemo={onWatchDemo} onStart={onStart} />
        </div>
      )}

      {/* ---------- READY ---------- */}
      {state === 'ready' && (
        <div>
          <div style={{ textAlign: 'center', marginBottom: 16 }}>
            <Sparkle size={40} twinkle />
            <Badge tone="success" dot style={{ marginTop: 8 }}>Ready to play</Badge>
            <h1 className="spk-h2" style={{ fontSize: 26, margin: '8px 0 6px' }}>{pet}&rsquo;s game is live!</h1>
            <p className="spk-muted" style={{ fontSize: 14, margin: 0 }}>Order #{orderRef} · play it forever.</p>
          </div>

          <Card surface="card" padding="md" style={{ marginBottom: 16 }}>
            <GameScene slotId="status-hero" label={`${pet.toUpperCase()} · LV 1`} />
          </Card>

          <Button as="a" href={(order && order.gameUrl) || ('https://sparkleclassic.com/' + slug)} variant="primary" size="lg" fullWidth leftIcon={<Icon name="play" />} style={{ marginBottom: 10 }}>
            Play {pet}&rsquo;s game
          </Button>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '9px 12px', background: 'var(--cream)', boxShadow: 'var(--ofx-edges)', marginBottom: 16 }}>
            <Icon name="link" size={16} aria-hidden="true" />
            <span style={{ fontFamily: 'var(--font-pixel)', fontSize: 9, color: 'var(--plum-ink)', flex: 1, wordBreak: 'break-all' }}>sparkleclassic.com/{slug}</span>
            <button onClick={copyLink} style={{ background: 'none', border: 'none', color: 'var(--plum-accent)', textDecoration: 'underline', cursor: 'pointer', fontSize: 12, fontWeight: 800 }}>Copy</button>
          </div>

          <Card surface="pink" padding="md" style={{ textAlign: 'center' }}>
            <h3 className="spk-h4" style={{ fontSize: 17, margin: '0 0 4px' }}>Loved it?</h3>
            <p style={{ margin: '0 0 12px', fontSize: 14, color: 'var(--plum-ink)' }}>Make your friend&rsquo;s pet next.</p>
            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', justifyContent: 'center' }}>
              <Button variant="secondary" onClick={onStart} leftIcon={<Icon name="plus" />}>Gift a game</Button>
              <Button variant="ghost" onClick={copyLink} leftIcon={<Icon name="link" />}>Share link</Button>
            </div>
          </Card>

          {/* Pixel Pals opt-in: asked here, at the moment of delight */}
          {wallState === 'idle' ? (
            <Card surface="card" padding="md" style={{ marginTop: 16 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                <span style={{ width: 34, height: 34, flex: '0 0 auto', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--cream)', color: 'var(--plum-ink)', boxShadow: 'var(--ofx-edges)' }}><Icon name="heart" /></span>
                <h3 className="spk-h4" style={{ fontSize: 17, margin: 0 }}>Feature {pet} on {WALL}?</h3>
              </div>
              <p className="spk-muted" style={{ margin: '0 0 12px', fontSize: 14 }}>Show {pet}&rsquo;s before and after on our pet wall and social media. Optional, and only after a quick review by our team.</p>
              <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', cursor: 'pointer', fontSize: 13.5, color: 'var(--plum-ink)', lineHeight: 1.5 }}>
                <input type="checkbox" checked={wallChecked} onChange={(e) => setWallChecked(e.target.checked)} style={{ marginTop: 3, width: 18, height: 18, flex: '0 0 auto' }} />
                <span>Yes, feature {pet}&rsquo;s photo and pixel art on {WALL} and social media. I agree to the <button type="button" onClick={() => setWallTermsOpen(true)} style={{ background: 'none', border: 0, color: 'var(--plum-accent)', textDecoration: 'underline', cursor: 'pointer', font: 'inherit', padding: 0 }}>wall terms</button>.</span>
              </label>
              <Button variant="secondary" disabled={!wallChecked || wallBusy} onClick={submitWall} leftIcon={<Icon name="heart" />} style={{ marginTop: 12 }}>{wallBusy ? 'Sending…' : `Add ${pet} to ${WALL}`}</Button>
            </Card>
          ) : (
            <Card surface="pink" padding="md" style={{ marginTop: 16, display: 'flex', gap: 10, alignItems: 'center' }}>
              <span style={{ width: 34, height: 34, flex: '0 0 auto', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--success)', color: 'var(--cream)', boxShadow: 'var(--ofx-edges)' }}><Icon name="check" /></span>
              <p style={{ margin: 0, fontSize: 14, color: 'var(--plum-ink)', fontWeight: 600 }}>Thanks! {pet} is in line for {WALL}. We&rsquo;ll review it before it goes public.</p>
            </Card>
          )}
        </div>
      )}

      {/* ---------- PHOTO UNREADABLE ---------- */}
      {state === 'photo' && (
        <div>
          <Card surface="card" padding="lg" style={{ marginBottom: 16, borderTop: 0 }}>
            <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
              <span style={{ width: 42, height: 42, flex: '0 0 auto', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--warning-tint)', color: 'var(--plum-ink)', boxShadow: 'var(--ofx-edges)', fontSize: 20 }}><Icon name="image" /></span>
              <div>
                <Badge tone="warning" dot>Action needed</Badge>
                <h1 className="spk-h4" style={{ fontSize: 19, margin: '8px 0 6px' }}>We couldn&rsquo;t read {pet}&rsquo;s photo</h1>
                <p style={{ margin: 0, fontSize: 14.5, color: 'var(--plum-ink)', lineHeight: 1.5 }}>
                  We could not read the photo. Please reply with another — clear, well-lit, and facing the camera works best. Everything else is saved.
                </p>
              </div>
            </div>
          </Card>
          <Button variant="primary" size="lg" fullWidth onClick={onFixPhoto} leftIcon={<Icon name="camera" />}>
            Send another photo
          </Button>
          <p className="spk-muted" style={{ textAlign: 'center', fontSize: 13, marginTop: 12 }}>
            Order #{orderRef} · your $29 is safe until your game is made.
          </p>
        </div>
      )}

      {/* ---------- REFUNDED ---------- */}
      {state === 'refunded' && (
        <div style={{ textAlign: 'center', padding: '20px 0' }}>
          <span style={{ width: 54, height: 54, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', background: 'var(--cream)', color: 'var(--plum-ink)', boxShadow: 'var(--ofx-edges)', fontSize: 24, marginBottom: 12 }}><Icon name="check" /></span>
          <h1 className="spk-h2" style={{ fontSize: 23, margin: '0 0 8px' }}>Your refund is on its way</h1>
          <p style={{ margin: '0 auto 6px', maxWidth: 320, fontSize: 15, color: 'var(--plum-ink)' }}>
            Your $29 has been refunded. You&rsquo;ll see it in 5 to 10 days.
          </p>
          <p className="spk-muted" style={{ fontSize: 13, margin: '0 0 22px' }}>Order #{orderRef}</p>
          <Button variant="secondary" onClick={onStart} leftIcon={<Icon name="heart" />}>Maybe another time</Button>
        </div>
      )}

      {/* quiet help + refund (not on refunded screen) */}
      {state !== 'refunded' && (
        <div style={{ display: 'flex', gap: 18, justifyContent: 'center', marginTop: 26, paddingTop: 16, borderTop: '2px solid var(--border-soft)' }}>
          <button onClick={() => setHelpOpen(true)} style={{ background: 'none', border: 'none', color: 'var(--plum-accent)', textDecoration: 'underline', cursor: 'pointer', fontSize: 13 }}>Get help</button>
          <button onClick={() => setRefundOpen(true)} style={{ background: 'none', border: 'none', color: 'var(--plum-accent)', textDecoration: 'underline', cursor: 'pointer', fontSize: 13 }}>Request a refund</button>
        </div>
      )}

      <Dialog open={refundOpen} onClose={() => setRefundOpen(false)}
        title={refundState === 'sent' ? 'Request received' : 'Request a refund'}
        footer={refundState === 'sent'
          ? <Button variant="primary" onClick={() => setRefundOpen(false)}>Close</Button>
          : (
            <React.Fragment>
              <Button variant="ghost" onClick={() => setRefundOpen(false)}>Keep my order</Button>
              <Button variant="primary" onClick={submitRefund} disabled={refundState === 'sending'}>
                {refundState === 'sending' ? 'Sending…' : 'Send request'}
              </Button>
            </React.Fragment>
          )}>
        {refundState === 'sent' ? (
          <p style={{ margin: 0, fontSize: 14.5, color: 'var(--plum-ink)', lineHeight: 1.5 }}>
            Thanks — a real person will review this and reply to <strong>{refundForm.email}</strong> within
            about a day. Often a quick fix is all it takes; if we can&rsquo;t make it right, we&rsquo;ll
            refund you in full.
          </p>
        ) : (
          <div>
            <p style={{ margin: '0 0 12px', fontSize: 14.5, color: 'var(--plum-ink)', lineHeight: 1.5 }}>
              Tell us what&rsquo;s wrong and we&rsquo;ll <strong>make it right or refund you</strong>. A real
              person reviews every request within about a day.
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <Input label="Your email" type="email" inputMode="email" placeholder="you@email.com"
                value={refundForm.email} onChange={(e) => setRefundForm((f) => ({ ...f, email: e.target.value }))} />
              <Textarea label="What went wrong? (optional)" rows={3} maxLength={1000}
                placeholder="e.g. the sprite doesn't quite look like my pet…"
                value={refundForm.reason} onChange={(e) => setRefundForm((f) => ({ ...f, reason: e.target.value }))} />
            </div>
            {refundErr && (
              <p role="alert" style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 10, color: 'var(--danger)', fontSize: 13, fontWeight: 700 }}>
                <Icon name="alert" size={15} aria-hidden="true" /> {refundErr}
              </p>
            )}
          </div>
        )}
      </Dialog>

      <Dialog open={helpOpen} onClose={() => setHelpOpen(false)} title="Need a hand?"
        footer={<Button variant="primary" onClick={() => setHelpOpen(false)}>Got it</Button>}>
        <p style={{ margin: '0 0 8px', fontSize: 14.5, color: 'var(--plum-ink)', lineHeight: 1.5 }}>
          Email <strong>help@sparkleclassic.com</strong> with your order number (#{orderRef}) and we&rsquo;ll reply within a day. A real person, every time.
        </p>
      </Dialog>

      <Dialog open={wallTermsOpen} onClose={() => setWallTermsOpen(false)} title={`${WALL} terms`}
        footer={<Button variant="primary" onClick={() => setWallTermsOpen(false)}>Got it</Button>}>
        <p style={{ margin: 0, fontSize: 13.5, color: 'var(--plum-ink)', lineHeight: 1.6 }}>{wallTerms ? wallTerms.text : 'Loading the terms…'}</p>
      </Dialog>

      {toast && (
        <div style={{ position: 'fixed', left: '50%', bottom: 18, transform: 'translateX(-50%)', zIndex: 1000, width: 'min(92%, 400px)' }}>
          <Toast tone={toast.tone} title={toast.title} onDismiss={() => setToast(null)}>{toast.msg}</Toast>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { StatusScreen });
