// solution-iphone.jsx — iPhone frame, CENTERED protagonist mode.
// El teléfono aparece centrado en el canvas cuando hay intervención del cliente,
// con el fondo oscurecido. Mensajes grandes, legibles.
//
// Props:
//   state    : 'idle' | 'chat' | 'sign' | 'happy'
//   lang     : 'es' | 'en'
//   dim      : boolean (faded during title cards)
//   time     : visible clock time
//   date     : visible date
//
//   For 'chat' state:
//     contactName, contactSubtitle, contactAvatar (emoji)
//     messages : array of { from: 'office'|'client', text, photoUrl?, timestamp? }
//     typing   : 'office'|'client'|null
//
//   For 'sign' state:
//     tapStep  : 0..3 (0 = unread, 1 = opened, 2 = T&C accepted, 3 = signed)
//
//   For 'happy' state:
//     phase    : 0..1 (controls emoji float-up)
//
// Exports on window: IPhone, PHONE_X, PHONE_Y, PHONE_W, PHONE_H, PHONE_SCALE

// Base phone size (designed for internal layout)
const PHONE_W = 244;
const PHONE_H = 528;
// Centered protagonist scale (~1.3× — larger for readability without overflow)
const PHONE_SCALE = 1.3;
// Centered position on 1280×720 canvas
const PHONE_X = (1280 - PHONE_W * PHONE_SCALE) / 2;  // ~481
const PHONE_Y = (720 - PHONE_H * PHONE_SCALE) / 2;   // ~17

function IPhone({
  state = 'idle',
  lang = 'es',
  dim = false,
  time = '4:09',
  date = 'mar, 16 mayo',
  contactName = 'EasyPro Plus',
  contactSubtitle = 'Tu asistente',
  contactAvatar = 'EP',
  messages = [],
  typing = null,
  tapStep = 0,
  phase = 0,
  // 0..1 — fade out + slide right as the phone exits (used in Act 5 Explain
  // when the cel hands off to the desktop "RFE letter" scene). 0 = fully in,
  // 1 = fully out (zero opacity, slid 320px right).
  exitProgress = 0,
}) {
  const t = (window.SOL_I18N && window.SOL_I18N[lang]) || {};
  const phoneName = t.phone_name || 'TOMÁS';

  const exitOpacity = 1 - exitProgress;
  const exitTranslateX = exitProgress * 320;

  return (
    <>
      {/* Backdrop dim — focuses attention on the phone */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'rgba(8, 6, 18, 0.62)',
        backdropFilter: 'blur(8px)',
        WebkitBackdropFilter: 'blur(8px)',
        zIndex: 29,
        opacity: (dim ? 0.45 : 1) * exitOpacity,
        animation: 'sol-phone-backdrop-in 420ms ease-out',
        pointerEvents: 'none',
      }} />

      <div style={{
        position: 'absolute',
        left: PHONE_X, top: PHONE_Y,
        width: PHONE_W, height: PHONE_H,
        zIndex: 30,
        opacity: (dim ? 0.55 : 1) * exitOpacity,
        transition: 'opacity 600ms ease',
        transform: `translateX(${exitTranslateX}px) scale(${PHONE_SCALE})`,
        transformOrigin: 'top left',
        filter: dim ? 'saturate(0.7)' : 'none',
        animation: exitProgress > 0 ? 'none' : 'sol-phone-in 420ms cubic-bezier(0.22, 1, 0.36, 1)',
      }}>
      {/* Outer bezel */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(155deg, #2a2a2e 0%, #1a1a1c 50%, #2a2a2e 100%)',
        borderRadius: 38,
        padding: 8,
        boxShadow: dim
          ? '0 12px 40px rgba(0,0,0,0.5)'
          : '0 20px 60px rgba(0,0,0,0.55), 0 0 0 1px rgba(255,255,255,0.06), 0 0 30px rgba(139, 92, 246, 0.12)',
      }}>
        {/* Screen */}
        <div style={{
          position: 'relative',
          width: '100%', height: '100%',
          borderRadius: 30,
          overflow: 'hidden',
          background: state === 'chat' || state === 'sign'
            ? '#0c0c0e'
            : 'linear-gradient(170deg, #1d1730 0%, #0c1525 60%, #050912 100%)',
        }}>
          {/* Dynamic island */}
          <div style={{
            position: 'absolute',
            top: 10,
            left: '50%',
            transform: 'translateX(-50%)',
            width: 84, height: 24,
            background: '#000',
            borderRadius: 14,
            zIndex: 5,
          }} />

          {/* Status bar */}
          <div style={{
            position: 'absolute',
            top: 14, left: 0, right: 0,
            display: 'flex',
            justifyContent: 'space-between',
            padding: '0 22px',
            fontSize: 12,
            fontWeight: 600,
            color: '#fff',
            letterSpacing: -0.01,
            zIndex: 6,
          }}>
            <span style={{ fontVariantNumeric: 'tabular-nums' }}>{time}</span>
            <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
              <svg width="16" height="10" viewBox="0 0 16 10" fill="white">
                <rect x="0" y="6" width="2.5" height="4" rx="0.5" />
                <rect x="4" y="4" width="2.5" height="6" rx="0.5" />
                <rect x="8" y="2" width="2.5" height="8" rx="0.5" />
                <rect x="12" y="0" width="2.5" height="10" rx="0.5" opacity="0.4" />
              </svg>
              <svg width="22" height="11" viewBox="0 0 22 11">
                <rect x="0.5" y="0.5" width="18" height="10" rx="2.5" fill="none" stroke="white" strokeOpacity="0.6"/>
                <rect x="19.5" y="3.5" width="2" height="4" rx="0.5" fill="white" fillOpacity="0.6"/>
                <rect x="2" y="2" width="13" height="7" rx="1" fill="white"/>
              </svg>
            </span>
          </div>

          {/* Body — by state */}
          {state === 'idle' && <IdleBody time={time} date={date} phoneName={phoneName} />}
          {state === 'chat' && (
            <ChatBody
              contactName={contactName}
              contactSubtitle={contactSubtitle}
              contactAvatar={contactAvatar}
              messages={messages}
              typing={typing}
            />
          )}
          {state === 'sign' && <SignBody tapStep={tapStep} />}
          {state === 'happy' && <HappyBody phase={phase} contactName={contactName} contactAvatar={contactAvatar} messages={messages} />}

          {/* Home indicator */}
          <div style={{
            position: 'absolute',
            bottom: 8,
            left: '50%',
            transform: 'translateX(-50%)',
            width: 100, height: 4,
            background: 'rgba(255,255,255,0.5)',
            borderRadius: 2,
          }} />
        </div>
      </div>
    </div>
    </>
  );
}

// ── IDLE state: lockscreen ──────────────────────────────────────────
function IdleBody({ time, date, phoneName }) {
  return (
    <div style={{
      position: 'absolute',
      inset: 0,
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      justifyContent: 'center',
      gap: 8,
      padding: '0 24px',
      textAlign: 'center',
    }}>
      <div style={{
        fontSize: 14, fontWeight: 500,
        color: 'rgba(255,255,255,0.7)',
        letterSpacing: -0.01,
        marginTop: -40,
      }}>{date}</div>
      <div style={{
        fontSize: 76, fontWeight: 200, color: '#fff',
        letterSpacing: -0.04,
        fontVariantNumeric: 'tabular-nums',
        lineHeight: 1, marginBottom: 18,
      }}>{time}</div>
      <div style={{
        width: 64, height: 64, borderRadius: '50%',
        background: 'linear-gradient(135deg, #fef3c7 0%, #f59e0b 100%)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 28, fontWeight: 500, color: '#7c2d12',
        border: '2px solid rgba(255,255,255,0.25)', marginBottom: 4,
      }}>T</div>
      <div style={{
        fontSize: 13, fontWeight: 500,
        color: 'rgba(255,255,255,0.92)',
        letterSpacing: 0.04, textTransform: 'uppercase',
      }}>{phoneName}</div>
    </div>
  );
}

// ── CHAT state: WhatsApp-style ──────────────────────────────────────
function ChatBody({ contactName, contactSubtitle, contactAvatar, messages, typing }) {
  return (
    <div style={{
      position: 'absolute',
      top: 38, bottom: 12, left: 0, right: 0,
      display: 'flex',
      flexDirection: 'column',
    }}>
      {/* Chat header */}
      <div style={{
        padding: '6px 12px 10px',
        display: 'flex',
        alignItems: 'center',
        gap: 8,
        borderBottom: '1px solid rgba(255,255,255,0.06)',
        background: '#1a1d24',
      }}>
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ flexShrink: 0 }}>
          <path d="M9 2l-5 5 5 5" stroke="#34d399" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
        {contactAvatar === 'EP' ? (
          <img
            src="../static/logo-mark.png"
            alt="EasyPro Plus"
            style={{
              width: 28, height: 28,
              flexShrink: 0,
              filter: 'drop-shadow(0 1px 4px rgba(0, 122, 255, 0.35))',
            }}
          />
        ) : (
          <div style={{
            width: 26, height: 26, borderRadius: '50%',
            background: 'linear-gradient(135deg, #4a8bff, #8b5cf6)',
            color: '#fff', fontSize: 10, fontWeight: 600,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0,
          }}>{contactAvatar}</div>
        )}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontSize: 11.5, fontWeight: 600, color: '#fff',
            letterSpacing: -0.005,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{contactName}</div>
          <div style={{
            fontSize: 9.5, color: 'rgba(255,255,255,0.5)',
            fontWeight: 400,
          }}>{contactSubtitle}</div>
        </div>
      </div>

      {/* Message list */}
      <div style={{
        flex: 1,
        overflow: 'hidden',
        padding: '8px 8px 4px',
        display: 'flex',
        flexDirection: 'column',
        gap: 6,
      }}>
        {messages.map((m, i) => <ChatBubble key={i} msg={m} />)}
        {typing && <TypingBubble side={typing === 'client' ? 'right' : 'left'} />}
      </div>

      {/* Input bar (just visual) */}
      <div style={{
        padding: '0 8px',
        display: 'flex',
        alignItems: 'center',
        gap: 6,
        height: 28,
      }}>
        <div style={{
          flex: 1,
          height: 22,
          background: '#1a1d24',
          borderRadius: 999,
          fontSize: 10,
          color: 'rgba(255,255,255,0.3)',
          padding: '0 10px',
          display: 'flex', alignItems: 'center',
        }}>Mensaje…</div>
        <div style={{
          width: 22, height: 22, borderRadius: '50%',
          background: '#25d366',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 10, color: '#000',
        }}>🎤</div>
      </div>
    </div>
  );
}

function ChatBubble({ msg }) {
  const isClient = msg.from === 'client';
  return (
    <div style={{
      maxWidth: '85%',
      alignSelf: isClient ? 'flex-end' : 'flex-start',
      background: isClient ? '#005c4b' : '#1f2c33',
      color: '#e5e7eb',
      padding: msg.photo ? 4 : '7px 9px',
      borderRadius: 10,
      fontSize: 11.5,
      lineHeight: 1.32,
      letterSpacing: -0.005,
      boxShadow: '0 1px 2px rgba(0,0,0,0.3)',
      animation: 'sol-bubble-in 240ms ease-out',
    }}>
      {msg.photo && (
        <div style={{
          width: 170, height: 110,
          background: msg.photoBg || 'linear-gradient(135deg, #6b7280 0%, #374151 100%)',
          borderRadius: 8,
          marginBottom: msg.text ? 4 : 0,
          padding: 8,
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'flex-start',
          fontFamily: 'ui-monospace, "SF Mono", monospace',
          fontSize: 5.5,
          color: '#000',
          overflow: 'hidden',
          position: 'relative',
        }}>
          {msg.photoContent || (
            <>
              <div style={{ fontSize: 8, fontWeight: 700, marginBottom: 3 }}>DHS · USCIS</div>
              <div>U.S. Department of Homeland Security</div>
              <div>U.S. Citizenship and Immigration Services</div>
              <div style={{ marginTop: 4, fontWeight: 700, fontSize: 6.5 }}>I-797E NOTICE OF ACTION</div>
              <div style={{ marginTop: 3 }}>{msg.photoBody || 'Request for Evidence...'}</div>
            </>
          )}
          <div style={{
            position: 'absolute',
            bottom: 6,
            left: 6, right: 6,
            height: 1,
            background: 'rgba(0,0,0,0.1)',
          }} />
        </div>
      )}
      {msg.text && (
        <div>{msg.text}</div>
      )}
      {msg.time && (
        <div style={{
          fontSize: 8,
          color: 'rgba(255,255,255,0.45)',
          textAlign: 'right',
          marginTop: 2,
          fontVariantNumeric: 'tabular-nums',
        }}>{msg.time} {isClient && <span style={{ color: '#3ec1ee' }}>✓✓</span>}</div>
      )}
    </div>
  );
}

function TypingBubble({ side }) {
  return (
    <div style={{
      maxWidth: '60%',
      alignSelf: side === 'right' ? 'flex-end' : 'flex-start',
      background: side === 'right' ? '#005c4b' : '#1f2c33',
      padding: '7px 12px',
      borderRadius: 10,
      display: 'flex',
      gap: 3,
    }}>
      {[0,1,2].map(i => (
        <span key={i} style={{
          width: 5, height: 5,
          borderRadius: '50%',
          background: 'rgba(255,255,255,0.6)',
          animation: `sol-typing 1s infinite ${i * 0.15}s`,
        }} />
      ))}
    </div>
  );
}

// ── SIGN state: contract sign ───────────────────────────────────────
function SignBody({ tapStep = 0 }) {
  const lang = (window.__solCurrentLang) || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const sn = i18n.sign || {};
  // 4 steps:
  //   0: notification on lockscreen
  //   1: contract open at top
  //   2: T&C checkbox marked
  //   3: signature drawn + ✓ Firmado
  const showNotif = tapStep === 0;
  const inApp = tapStep >= 1;

  return (
    <div style={{
      position: 'absolute',
      top: 38, bottom: 12, left: 0, right: 0,
      padding: '0 12px',
      display: 'flex',
      flexDirection: 'column',
    }}>
      {showNotif && (
        <div style={{
          marginTop: 80,
          background: 'rgba(60, 60, 65, 0.85)',
          backdropFilter: 'blur(20px)',
          borderRadius: 14,
          padding: '10px 12px',
          color: '#fff',
          animation: 'sol-bubble-in 260ms ease-out',
        }}>
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: 6,
            fontSize: 9,
            color: 'rgba(255,255,255,0.7)',
            marginBottom: 4,
          }}>
            <img
              src="../static/logo-mark.png"
              alt="EasyPro Plus"
              style={{
                width: 16, height: 16,
                flexShrink: 0,
              }}
            />
            <span>EasyPro Plus · ahora</span>
          </div>
          <div style={{ fontSize: 11, fontWeight: 600, marginBottom: 2 }}>
            {lang === 'en' ? 'Contract ready to sign' : 'Contrato listo para firmar'}
          </div>
          <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.65)', lineHeight: 1.3 }}>
            {lang === 'en' ? 'Family-based AOS Residency Package. Tap to review and sign.' : 'Paquete Residencia Family-based AOS. Toca para revisar y firmar.'}
          </div>
        </div>
      )}

      {inApp && (
        <>
          <div style={{
            padding: '6px 0 8px',
            borderBottom: '1px solid rgba(255,255,255,0.06)',
            color: '#fff',
            fontSize: 11,
            fontWeight: 600,
            letterSpacing: -0.005,
          }}>
            <div style={{ fontSize: 9, color: 'rgba(255,255,255,0.5)', marginBottom: 2 }}>EasyPro Plus · Sign</div>
            {(sn.title_pre || 'Contrato · ')}{lang === 'en' ? 'AOS Package' : 'Paquete AOS'}
          </div>

          {/* Contract preview */}
          <div style={{
            flex: 1,
            background: 'rgba(255,255,255,0.04)',
            borderRadius: 8,
            padding: 8,
            marginTop: 8,
            overflow: 'hidden',
            fontFamily: 'ui-monospace, "SF Mono", monospace',
            fontSize: 6.5,
            lineHeight: 1.4,
            color: 'rgba(255,255,255,0.7)',
          }}>
            <div style={{ fontWeight: 700, fontSize: 8, color: '#fff', marginBottom: 4 }}>
              Engagement Letter — Family-based AOS
            </div>
            <div>Client: TOMÁS SMITH (US Citizen, sponsor)</div>
            <div>Beneficiary: CARLA A. VERA RODRÍGUEZ</div>
            <div>Date: May 16, 2026</div>
            <div style={{ marginTop: 4 }}>
              I-130 + I-130A + I-485 + I-864 (concurrent filing). Optional I-765, I-131.
              USCIS filing fees not included.
            </div>
            <div style={{ marginTop: 6, paddingTop: 6, borderTop: '1px solid rgba(255,255,255,0.08)' }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 7, color: '#fff' }}>
                <span style={{
                  width: 10, height: 10,
                  border: '1px solid rgba(255,255,255,0.4)',
                  borderRadius: 2,
                  background: tapStep >= 2 ? '#34C759' : 'transparent',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  flexShrink: 0,
                  color: '#fff',
                  fontSize: 8,
                }}>{tapStep >= 2 ? '✓' : ''}</span>
                {sn.accept_terms || 'Acepto los términos y condiciones'}
              </label>
            </div>

            {/* Signature area */}
            <div style={{
              marginTop: 10,
              padding: 8,
              border: '1px dashed rgba(255,255,255,0.2)',
              borderRadius: 6,
              minHeight: 36,
              position: 'relative',
            }}>
              <div style={{ fontSize: 6, color: 'rgba(255,255,255,0.4)', marginBottom: 2 }}>
                {sn.signature_label || 'Firma:'}
              </div>
              {tapStep >= 3 ? (
                <svg width="100" height="20" viewBox="0 0 100 20" style={{ display: 'block' }}>
                  <path d="M 4 14 Q 12 4, 20 12 T 36 10 Q 44 18, 52 8 T 70 12 Q 82 4, 96 10"
                        stroke="#34d399" strokeWidth="1.5" fill="none" strokeLinecap="round"/>
                </svg>
              ) : (
                <div style={{ height: 12 }} />
              )}
            </div>

            {tapStep >= 3 && (
              <div style={{
                marginTop: 8,
                padding: '6px 8px',
                background: 'rgba(52, 199, 89, 0.15)',
                border: '1px solid rgba(52, 199, 89, 0.4)',
                borderRadius: 5,
                color: '#34C759',
                fontSize: 8,
                fontWeight: 600,
                textAlign: 'center',
                animation: 'sol-bubble-in 280ms ease-out',
              }}>
                {sn.signed_badge_pre || '✓ Firmado · '}{sn.signed_date || new Date().toLocaleDateString('es', { day: '2-digit', month: 'short' })}
              </div>
            )}
          </div>

          <button style={{
            margin: '8px 0 4px',
            background: tapStep >= 3 ? '#34C759' : '#007AFF',
            color: '#fff',
            border: 0,
            borderRadius: 8,
            padding: '8px',
            fontSize: 10,
            fontWeight: 600,
            cursor: 'pointer',
          }}>
            {tapStep >= 3 ? (lang === 'en' ? '✓ Sent' : '✓ Enviado') : tapStep === 2 ? (lang === 'en' ? 'Tap to sign' : 'Tocar para firmar') : (lang === 'en' ? 'Check and continue' : 'Marcar y continuar')}
          </button>
        </>
      )}

      {/* Tap pulse on current target */}
      {tapStep < 3 && (
        <div style={{
          position: 'absolute',
          left: '50%',
          top: tapStep === 0 ? '38%' : (tapStep === 1 ? '64%' : '54%'),
          transform: 'translate(-50%, -50%)',
          width: 28, height: 28,
          borderRadius: '50%',
          background: 'rgba(255,255,255,0.3)',
          animation: 'sol-tap-pulse 1.2s ease-out infinite',
          pointerEvents: 'none',
        }} />
      )}
    </div>
  );
}

// ── HAPPY state: chat + floating emojis ─────────────────────────────
function HappyBody({ phase = 0, contactName, contactAvatar, messages = [] }) {
  // Render chat in background, then floating emojis on top
  const emojis = ['✨', '🙏', '❤️', '💙', '🥹', '🎉'];
  const count = 8;

  return (
    <>
      <ChatBody
        contactName={contactName}
        contactSubtitle="en línea · hace un momento"
        contactAvatar={contactAvatar}
        messages={messages}
        typing={null}
      />

      {/* Floating emojis */}
      <div style={{
        position: 'absolute',
        inset: 0,
        pointerEvents: 'none',
        overflow: 'hidden',
      }}>
        {Array.from({ length: count }).map((_, i) => {
          const seed = i / count;
          const localPhase = (phase * 1.2 - seed * 0.4 + 1) % 1;
          if (localPhase < 0 || localPhase > 1) return null;
          const left = 30 + (i * 23) % (PHONE_W - 60);
          const startY = PHONE_H - 80;
          const endY = 60;
          const y = startY + (endY - startY) * Easing.easeOutCubic(localPhase);
          const opacity = localPhase < 0.7 ? 1 : 1 - (localPhase - 0.7) / 0.3;
          const wobble = Math.sin(localPhase * Math.PI * 3 + i) * 8;
          const emoji = emojis[i % emojis.length];
          const size = 18 + (i % 3) * 4;
          return (
            <div key={i} style={{
              position: 'absolute',
              left: left + wobble,
              top: y,
              fontSize: size,
              opacity,
              willChange: 'transform, opacity',
              filter: 'drop-shadow(0 2px 8px rgba(139, 92, 246, 0.4))',
            }}>{emoji}</div>
          );
        })}
      </div>
    </>
  );
}

// Add keyframes once
if (typeof document !== 'undefined' && !document.getElementById('sol-iphone-anim')) {
  const s = document.createElement('style');
  s.id = 'sol-iphone-anim';
  s.textContent = `
    @keyframes sol-phone-in {
      from { opacity: 0; transform: scale(${PHONE_SCALE * 0.92}) translateY(20px); }
      to   { opacity: 1; transform: scale(${PHONE_SCALE}) translateY(0); }
    }
    @keyframes sol-phone-backdrop-in {
      from { opacity: 0; }
      to   { opacity: 1; }
    }
    @keyframes sol-bubble-in {
      from { opacity: 0; transform: translateY(8px) scale(0.96); }
      to   { opacity: 1; transform: translateY(0) scale(1); }
    }
    @keyframes sol-typing {
      0%, 60%, 100% { opacity: 0.3; transform: translateY(0); }
      30%           { opacity: 1;   transform: translateY(-2px); }
    }
    @keyframes sol-tap-pulse {
      0%   { transform: translate(-50%, -50%) scale(0.6); opacity: 0.9; }
      100% { transform: translate(-50%, -50%) scale(2.2); opacity: 0; }
    }
  `;
  document.head.appendChild(s);
}

Object.assign(window, { IPhone, PHONE_X, PHONE_Y, PHONE_W, PHONE_H });
