/* Studio — "Action needed" photo-review escalation (used by the order screen).
   Flag → email a per-order upload link → reminders → if no reply, offer a refund. */
const Spf = window.SparkleClassicDesignSystem_7a1470;

const REASON_OPTIONS = ['Too dark', 'Blurry', 'Pet not facing camera', 'More than one pet', 'Too far away', 'Heavy filter / obscured'];

function EscalationSteps({ index }) {
  const labels = ['Review photo', 'Request new photo', 'Await reply', 'Offer refund'];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', marginBottom: 16 }}>
      {labels.map((l, i) => {
        const done = i < index, current = i === index;
        return (
          <React.Fragment key={l}>
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 6, padding: '5px 10px',
              fontFamily: 'var(--font-body)', fontWeight: 800, fontSize: 12, whiteSpace: 'nowrap', boxShadow: 'var(--ofx-edges)',
              background: current ? 'var(--action)' : done ? 'var(--success)' : 'var(--cream-surface)',
              color: current || done ? 'var(--cream)' : 'var(--plum-accent)',
            }}>
              <span style={{ fontFamily: 'var(--font-pixel)', fontSize: 8 }}>{done ? '✓' : i + 1}</span>{l}
            </span>
            {i < labels.length - 1 && <span style={{ width: 12, height: 3, background: 'var(--plum-ink)', flex: '0 0 auto' }} />}
          </React.Fragment>
        );
      })}
    </div>
  );
}

function PhotoReview({ order, role, onActivity, onResolve }) {
  const { Button, Card, Badge, Icon, Dialog, Textarea, Input } = Spf;
  const [phase, setPhase] = React.useState('reviewing');
  const [composer, setComposer] = React.useState(false);
  const [refund, setRefund] = React.useState(false);
  const [reasons, setReasons] = React.useState([REASON_OPTIONS.find((r) => (order.actionReason || '').toLowerCase().includes(r.toLowerCase().split(' ')[0])) || 'Too dark']);
  const [copied, setCopied] = React.useState(false);
  const first = order.customer.split(' ')[0];
  const link = `sparkleclassic.com/u/${order.id}`;
  const reasonPhrase = () => {
    const rs = reasons.length ? reasons : ['Hard to trace'];
    const r0 = rs[0].toLowerCase();
    const map = { 'too dark': 'a little too dark to trace', 'blurry': 'a bit blurry', 'pet not facing camera': 'angled away from the camera', 'more than one pet': 'showing more than one pet', 'too far away': 'a little too far away', 'heavy filter / obscured': 'hard to read under the filter' };
    return map[r0] || r0;
  };
  const uploadHref = () => `upload.html?order=${encodeURIComponent(order.id)}&pet=${encodeURIComponent(order.petName)}&reason=${encodeURIComponent(reasonPhrase())}`;
  const openUpload = () => window.open(uploadHref(), '_blank', 'noopener');
  const log = (t, icon) => onActivity && onActivity({ t, icon, when: 'Just now · you' });

  const toggleReason = (r) => setReasons((rs) => rs.includes(r) ? rs.filter((x) => x !== r) : [...rs, r]);
  const reasonText = (reasons.length ? reasons : ['it’s hard to trace']).map((r) => r.toLowerCase()).join(', ');
  const buildBody = () => `Hi ${first},\n\nThanks for your order! We’ve started on ${order.petName}’s game, but the photo we have is tricky to work from (${reasonText}).\n\nCould you send one more? Your private upload link drops the photo straight onto your order — no account needed:\n\n${link}\n\nOne clear, well-lit photo facing the camera is perfect. As soon as it lands we’ll get ${order.petName} into the game — about 24 hours.\n\n— The Sparkle Classic team`;
  const [body, setBody] = React.useState(buildBody());
  React.useEffect(() => { setBody(buildBody()); /* eslint-disable-next-line */ }, [reasons.join('|')]);

  const sendRequest = () => { setComposer(false); setPhase('awaiting'); log('New-photo request emailed', 'mail'); };
  const sendReminder = () => log('Reminder email sent', 'reload');
  const markNoReply = () => { setPhase('noResponse'); onActivity && onActivity({ t: 'No reply after 48 hours', icon: 'clock', when: 'Just now' }); };
  const markReceived = () => { setPhase('received'); onActivity && onActivity({ t: 'Customer uploaded a new photo', icon: 'image', when: 'Just now' }); };
  const approve = () => { setPhase('approved'); log('New photo approved — back in build queue', 'check'); onResolve && onResolve('art'); };
  const doRefund = () => { setRefund(false); setPhase('refunded'); log(`Refund issued (${order.amount})`, 'check'); onResolve && onResolve('refunded'); };

  const stepIndex = { reviewing: 0, awaiting: 2, noResponse: 3, received: 2, approved: 1, refunded: 3 }[phase];
  const copy = () => { setCopied(true); setTimeout(() => setCopied(false), 1600); };

  return (
    <Card surface="card" padding="lg" style={{ boxShadow: 'var(--ofx-edges), var(--shadow-block)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
        <span style={{ width: 30, height: 30, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--warning-tint)', color: 'var(--plum-ink)', boxShadow: 'var(--ofx-edges)' }}><Icon name="alert" size={16} /></span>
        <h2 className="spk-h3" style={{ fontSize: 20, margin: 0, whiteSpace: 'nowrap' }}>Action needed: photo</h2>
      </div>
      <p className="spk-muted" style={{ margin: '0 0 16px', fontSize: 14 }}>
        This photo isn’t usable yet ({order.actionReason}). Ask for a better one, then escalate to a refund if they don’t reply.
      </p>

      <EscalationSteps index={stepIndex} />

      <div style={{ display: 'flex', gap: 12, marginBottom: 18, flexWrap: 'wrap' }}>
        <div style={{ position: 'relative' }}>
          <image-slot id={`spf-${order.id}-photo`} shape="rect" fit="cover" placeholder="Their photo" style={{ width: '110px', height: '110px', boxShadow: 'var(--ofx-edges)' }}></image-slot>
          {(phase === 'reviewing' || phase === 'awaiting' || phase === 'noResponse') && (
            <span style={{ position: 'absolute', top: 6, left: 6, fontFamily: 'var(--font-pixel)', fontSize: 7, color: 'var(--cream)', background: 'var(--danger)', padding: '3px 5px', boxShadow: 'var(--ofx-edges)' }}>FLAGGED</span>
          )}
        </div>
        {phase === 'received' && (
          <div style={{ position: 'relative' }}>
            <image-slot id={`spf-${order.id}-photo2`} shape="rect" fit="cover" placeholder="New photo" style={{ width: '110px', height: '110px', boxShadow: 'var(--ofx-edges)', background: 'var(--mint)' }}></image-slot>
            <span style={{ position: 'absolute', top: 6, left: 6, fontFamily: 'var(--font-pixel)', fontSize: 7, color: 'var(--cream)', background: 'var(--success)', padding: '3px 5px', boxShadow: 'var(--ofx-edges)' }}>NEW</span>
          </div>
        )}
        <div style={{ flex: 1, minWidth: 150, alignSelf: 'center' }}>
          <div style={{ fontFamily: 'var(--font-pixel)', fontSize: 8, color: 'var(--plum-accent)', marginBottom: 6 }}>FLAGGED BECAUSE</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {reasons.map((r) => <span key={r} style={{ fontSize: 12, fontWeight: 700, color: 'var(--plum-ink)', background: 'var(--warning-tint)', boxShadow: 'var(--ofx-edges)', padding: '4px 9px' }}>{r}</span>)}
          </div>
        </div>
      </div>

      <div style={{ boxShadow: 'var(--ofx-edges)', background: 'var(--cream)', padding: 16 }}>
        {phase === 'reviewing' && (
          <div>
            <strong style={{ display: 'block', fontSize: 15, color: 'var(--plum-ink)', marginBottom: 4 }}>Is this photo usable?</strong>
            <p className="spk-muted" style={{ margin: '0 0 12px', fontSize: 13.5 }}>Approve to keep building, or ask the customer for a better one.</p>
            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              <Button variant="primary" leftIcon={<Icon name="mail" />} onClick={() => setComposer(true)}>Request a better photo</Button>
              <Button variant="secondary" leftIcon={<Icon name="check" />} onClick={approve}>Photo’s fine — approve</Button>
            </div>
          </div>
        )}
        {phase === 'awaiting' && (
          <div>
            <Badge tone="warning" dot>Waiting on customer</Badge>
            <strong style={{ display: 'block', fontSize: 15, color: 'var(--plum-ink)', margin: '8px 0 4px' }}>Upload request sent to {order.email}</strong>
            <p className="spk-muted" style={{ margin: '0 0 12px', fontSize: 13.5 }}>They can drop a new photo at <strong style={{ color: 'var(--plum-ink)' }}>{link}</strong>. We’ll auto-resume when it lands.</p>
            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              <Button variant="primary" leftIcon={<Icon name="reload" />} onClick={sendReminder}>Send reminder</Button>
              <Button variant="secondary" leftIcon={<Icon name="external-link" />} onClick={openUpload}>Open their upload page</Button>
              <Button variant="ghost" leftIcon={<Icon name="image" />} onClick={markReceived}>Add photo for them</Button>
            </div>
            <p className="spk-muted" style={{ margin: '12px 0 0', fontSize: 12.5, display: 'flex', alignItems: 'center', gap: 6 }}>
              <Icon name="clock" size={14} aria-hidden="true" /> A refund becomes the next step if we don’t hear back in 48 hours.
              <button onClick={markNoReply} style={{ background: 'none', border: 0, color: 'var(--plum-accent)', textDecoration: 'underline', cursor: 'pointer', fontSize: 12 }}>Simulate →</button>
            </p>
          </div>
        )}
        {phase === 'noResponse' && (
          <div>
            <Badge tone="danger" dot>No response in 48h</Badge>
            <strong style={{ display: 'block', fontSize: 15, color: 'var(--plum-ink)', margin: '8px 0 4px' }}>Next step: offer {first} a refund</strong>
            <p className="spk-muted" style={{ margin: '0 0 12px', fontSize: 13.5 }}>We emailed and reminded {first}, but no new photo arrived. Offer a full {order.amount} refund, or nudge once more.</p>
            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              {can(role, 'confirmRefund')
                ? <Button variant="primary" leftIcon={<Icon name="mail" />} onClick={() => setRefund(true)}>Offer a refund</Button>
                : <Button variant="primary" leftIcon={<Icon name="mail" />} onClick={() => setRefund(true)}>Request a refund</Button>}
              <Button variant="ghost" leftIcon={<Icon name="reload" />} onClick={sendReminder}>One more reminder</Button>
              <Button variant="ghost" leftIcon={<Icon name="image" />} onClick={markReceived}>They replied — add photo</Button>
            </div>
          </div>
        )}
        {phase === 'received' && (
          <div>
            <Badge tone="success" dot>New photo in</Badge>
            <strong style={{ display: 'block', fontSize: 15, color: 'var(--plum-ink)', margin: '8px 0 4px' }}>{order.petName}’s new photo is ready to check</strong>
            <p className="spk-muted" style={{ margin: '0 0 12px', fontSize: 13.5 }}>Approve to drop it back into the build queue.</p>
            <Button variant="primary" leftIcon={<Icon name="check" />} onClick={approve}>Approve &amp; resume build</Button>
          </div>
        )}
        {phase === 'approved' && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ width: 34, height: 34, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--success)', color: 'var(--cream)', boxShadow: 'var(--ofx-edges)' }}><Icon name="check" /></span>
            <div><strong style={{ fontSize: 15, color: 'var(--plum-ink)' }}>Photo approved</strong><div className="spk-muted" style={{ fontSize: 13 }}>{order.petName} is back in the build queue.</div></div>
          </div>
        )}
        {phase === 'refunded' && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ width: 34, height: 34, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--plum-ink)', color: 'var(--cream)', boxShadow: 'var(--ofx-edges)' }}><Icon name="check" /></span>
            <div><strong style={{ fontSize: 15, color: 'var(--plum-ink)' }}>Refunded {order.amount}</strong><div className="spk-muted" style={{ fontSize: 13 }}>{first} was emailed. Funds arrive in 5–10 days.</div></div>
          </div>
        )}
      </div>

      <Dialog open={composer} onClose={() => setComposer(false)} title="Request a new photo"
        footer={<React.Fragment>
          <Button variant="ghost" onClick={() => setComposer(false)}>Cancel</Button>
          <Button variant="primary" leftIcon={<Icon name="mail" />} onClick={sendRequest}>Send request</Button>
        </React.Fragment>}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, textAlign: 'left' }}>
          <Input label="To" defaultValue={order.email} readOnly />
          <Input label="Subject" defaultValue={`A quick fix for ${order.petName}’s game`} />
          <div>
            <span className="spk-field__label" style={{ display: 'block', fontWeight: 700, color: 'var(--plum-ink)', marginBottom: 8 }}>What’s wrong with the photo?</span>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {REASON_OPTIONS.map((r) => {
                const on = reasons.includes(r);
                return <button key={r} onClick={() => toggleReason(r)} aria-pressed={on} style={{ fontSize: 12.5, fontWeight: 700, cursor: 'pointer', padding: '6px 11px', border: 0, boxShadow: 'var(--ofx-edges)', background: on ? 'var(--action)' : 'var(--cream-surface)', color: on ? 'var(--cream)' : 'var(--plum-ink)' }}>{r}</button>;
              })}
            </div>
          </div>
          <div>
            <span className="spk-field__label" style={{ display: 'block', fontWeight: 700, color: 'var(--plum-ink)', marginBottom: 6 }}>Their private upload link</span>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', background: 'var(--cream)', boxShadow: 'var(--ofx-edges)' }}>
              <Icon name="link" size={16} aria-hidden="true" />
              <span style={{ fontFamily: 'var(--font-pixel)', fontSize: 10, color: 'var(--plum-ink)', flex: 1, wordBreak: 'break-all' }}>{link}</span>
              <button onClick={openUpload} style={{ background: 'none', border: 0, color: 'var(--plum-accent)', textDecoration: 'underline', cursor: 'pointer', fontSize: 12, fontWeight: 800, display: 'inline-flex', alignItems: 'center', gap: 4 }}>Open <Icon name="external-link" size={12} /></button>
              <button onClick={copy} style={{ background: 'none', border: 0, color: 'var(--plum-accent)', textDecoration: 'underline', cursor: 'pointer', fontSize: 12, fontWeight: 800 }}>{copied ? 'Copied' : 'Copy'}</button>
            </div>
            <p className="spk-muted" style={{ margin: '6px 0 0', fontSize: 12 }}>Opens a 1-tap uploader bound to {order.id}. No login. New photo lands straight on the order.</p>
          </div>
          <Textarea label="Message" rows={8} value={body} onChange={(e) => setBody(e.target.value)} />
        </div>
      </Dialog>

      <Dialog open={refund} onClose={() => setRefund(false)} title={can(role, 'confirmRefund') ? `Refund ${order.customer}?` : `Request a refund for ${order.customer}?`}
        footer={<React.Fragment>
          <Button variant="ghost" onClick={() => setRefund(false)}>Cancel</Button>
          {can(role, 'confirmRefund')
            ? <Button variant="danger" onClick={doRefund}>Refund {order.amount}</Button>
            : <Button variant="primary" onClick={() => { setRefund(false); log('Refund requested — sent to admin', 'mail'); }}>Send request to admin</Button>}
        </React.Fragment>}>
        <p style={{ margin: 0, fontSize: 14.5, color: 'var(--plum-ink)', lineHeight: 1.5 }}>
          {can(role, 'confirmRefund')
            ? <span>This refunds {order.customer} {order.amount} in full via Stripe and closes the order. We’ll email: “Your {order.amount} has been refunded; you’ll see it in 5 to 10 days.”</span>
            : <span>You can request this refund, but an admin confirms it. They’ll get a note to approve {order.amount} back to {order.customer}.</span>}
        </p>
      </Dialog>
    </Card>
  );
}

Object.assign(window, { PhotoReview, EscalationSteps, REASON_OPTIONS });
