// ─── Área do Paciente v4 — Câmera Guiada + Consent LGPD ─────────────────────
const { useState: useStateP, useRef: useRefP, useEffect: useEffectP, useCallback: useCallbackP } = React;

// ─── Avaliação de qualidade da imagem via canvas ─────────────────────────────
function analyzeImageQuality(file) {
  return new Promise((resolve) => {
    if (!file.type.startsWith('image/')) { resolve({ ok: true, warnings: [] }); return; }
    const img = new Image();
    const url = URL.createObjectURL(file);
    img.onload = () => {
      URL.revokeObjectURL(url);
      const warnings = [];
      const MIN_W = 800, MIN_H = 600;
      if (img.width < MIN_W || img.height < MIN_H) {
        warnings.push(`Imagem pequena (${img.width}×${img.height}px) — pode dificultar a leitura`);
      }
      // Verificar blur: amostrar canvas 100×100 e calcular variância
      const canvas = document.createElement('canvas');
      const SIZE = 100;
      canvas.width = SIZE; canvas.height = SIZE;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0, SIZE, SIZE);
      const data = ctx.getImageData(0, 0, SIZE, SIZE).data;
      const grays = [];
      for (let i = 0; i < data.length; i += 4) {
        grays.push(0.299 * data[i] + 0.587 * data[i+1] + 0.114 * data[i+2]);
      }
      const mean = grays.reduce((a, b) => a + b, 0) / grays.length;
      const variance = grays.reduce((s, v) => s + (v - mean) ** 2, 0) / grays.length;
      if (variance < 200) {
        warnings.push('Foto pode estar desfocada — tente tirar novamente em boa iluminação');
      }
      resolve({ ok: warnings.length === 0, warnings });
    };
    img.onerror = () => { URL.revokeObjectURL(url); resolve({ ok: true, warnings: [] }); };
    img.src = url;
  });
}

// ─── Compressão de imagem antes do upload ────────────────────────────────────
// Reduz imagens acima de MAX_IMAGE_BYTES para caber no limite do Blob sem perder
// legibilidade clínica. PDFs passam direto (não são imagens).
const MAX_IMAGE_BYTES = 8 * 1024 * 1024; // 8 MB — teto antes de comprimir

function compressImage(file) {
  return new Promise((resolve) => {
    if (!file.type.startsWith('image/') || file.size <= MAX_IMAGE_BYTES) {
      resolve(file);
      return;
    }
    const img = new Image();
    const url = URL.createObjectURL(file);
    img.onload = () => {
      URL.revokeObjectURL(url);

      // Escala proporcional: reduz até que a área seja compatível com ~8 MB JPEG.
      // Fator empírico: JPEG q=0.85 ≈ 3–4 bytes/px → 8 MB ≈ 2M px → ~1414×1414.
      // Para laudos A4 em retrato, mantemos resolução maior que o mínimo legível.
      const MAX_AREA = 4_000_000; // px² — mantém até ~2000×2000
      const area = img.width * img.height;
      const scale = area > MAX_AREA ? Math.sqrt(MAX_AREA / area) : 1;
      const w = Math.round(img.width * scale);
      const h = Math.round(img.height * scale);

      const canvas = document.createElement('canvas');
      canvas.width = w;
      canvas.height = h;
      canvas.getContext('2d').drawImage(img, 0, 0, w, h);

      canvas.toBlob(
        (blob) => {
          if (!blob || blob.size >= file.size) { resolve(file); return; }
          resolve(new File([blob], file.name, { type: 'image/jpeg', lastModified: Date.now() }));
        },
        'image/jpeg',
        0.85,
      );
    };
    img.onerror = () => { URL.revokeObjectURL(url); resolve(file); };
    img.src = url;
  });
}

// ─── Modal de orientação para câmera ─────────────────────────────────────────
const CameraGuideModal = ({ onClose, onCapture }) => {
  const C = {
    dark: '#1E3326', mid: '#2C4A35', sage: '#5C8A6E',
    cream: '#F8F5EF', border: '#EDE9E2', muted: '#8FAA96', text: '#1A2B1E',
  };
  const tips = [
    { icon: '💡', text: 'Fotografe em local bem iluminado — luz natural é ideal' },
    { icon: '📐', text: 'Segure o celular paralelo ao papel, sem inclinar' },
    { icon: '🔍', text: 'Enquadre todo o documento — margens incluídas' },
    { icon: '🤚', text: 'Apoie o cotovelo para evitar tremido' },
  ];

  return (
    <div style={{position:'fixed',inset:0,background:'rgba(0,0,0,0.6)',zIndex:1000,display:'flex',alignItems:'flex-end',justifyContent:'center'}}
      onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={{background:C.cream,borderRadius:'24px 24px 0 0',padding:'28px 24px 40px',width:'100%',maxWidth:480,boxShadow:'0 -8px 40px rgba(0,0,0,0.2)'}}>
        <div style={{width:40,height:4,borderRadius:2,background:C.border,margin:'0 auto 24px'}}/>
        <h3 style={{fontSize:18,fontWeight:700,color:C.text,margin:'0 0 6px',fontFamily:'Lora, serif'}}>
          Como tirar uma boa foto
        </h3>
        <p style={{fontSize:13,color:C.muted,margin:'0 0 20px',lineHeight:1.6}}>
          Siga as dicas abaixo para garantir que o texto do laudo fique legível.
        </p>

        {/* Área de preview visual do enquadramento */}
        <div style={{background:'#1A2B1E',borderRadius:16,padding:'16px',marginBottom:20,position:'relative',overflow:'hidden'}}>
          <div style={{width:'100%',paddingTop:'56%',position:'relative'}}>
            <div style={{position:'absolute',inset:0,display:'flex',alignItems:'center',justifyContent:'center'}}>
              {/* Documento simulado */}
              <div style={{width:'65%',height:'80%',border:'2px dashed rgba(92,138,110,0.8)',borderRadius:8,display:'flex',alignItems:'center',justifyContent:'center',position:'relative'}}>
                <div style={{textAlign:'center'}}>
                  <div style={{fontSize:24,marginBottom:4}}>📄</div>
                  <div style={{fontSize:10,color:'rgba(92,138,110,0.9)',fontWeight:600,letterSpacing:'0.05em'}}>ENQUADRE AQUI</div>
                </div>
                {/* Cantos do guia */}
                {[['0%','0%',0],['100%','0%',90],['100%','100%',180],['0%','100%',270]].map(([r,b,rot], i) => (
                  <div key={i} style={{position:'absolute',right:r==='100%'?-2:'auto',left:r==='0%'?-2:'auto',top:b==='0%'?-2:'auto',bottom:b==='100%'?-2:'auto',width:16,height:16,borderTop:`3px solid #5C8A6E`,borderLeft:`3px solid #5C8A6E`,transform:`rotate(${rot}deg)`,borderRadius:'2px 0 0 0'}}/>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* Dicas */}
        <div style={{display:'flex',flexDirection:'column',gap:10,marginBottom:24}}>
          {tips.map((t, i) => (
            <div key={i} style={{display:'flex',alignItems:'center',gap:12,padding:'10px 14px',background:'#fff',borderRadius:12,border:`1px solid ${C.border}`}}>
              <span style={{fontSize:20,flexShrink:0}}>{t.icon}</span>
              <span style={{fontSize:13,color:C.text,lineHeight:1.4}}>{t.text}</span>
            </div>
          ))}
        </div>

        <button onClick={onCapture}
          style={{width:'100%',padding:'16px',borderRadius:14,border:'none',background:C.mid,color:'#fff',fontSize:15,fontWeight:700,cursor:'pointer',fontFamily:'inherit',letterSpacing:'0.01em',boxShadow:'0 6px 20px rgba(44,74,53,0.28)'}}>
          Abrir câmera
        </button>
        <button onClick={onClose}
          style={{width:'100%',padding:'12px',marginTop:10,borderRadius:14,border:`1.5px solid ${C.border}`,background:'transparent',color:C.muted,fontSize:14,fontWeight:600,cursor:'pointer',fontFamily:'inherit'}}>
          Cancelar
        </button>
      </div>
    </div>
  );
};

// ─── Área do Paciente ─────────────────────────────────────────────────────────
const PatientArea = ({ envId }) => {
  const C = {
    dark: '#1E3326', mid: '#2C4A35', light: '#3A6347', sage: '#5C8A6E',
    cream: '#F8F5EF', border: '#EDE9E2', borderLight: '#F0ECE4',
    muted: '#8FAA96', text: '#1A2B1E', subtext: '#4A6355',
    white: '#fff', red: '#B84040', redBg: '#FFF0F0', redBorder: '#F5C5C5',
    amber: '#8A6A20', amberBg: '#FBF5E6',
  };

  const [env, setEnv]         = useStateP(
    (window.MOCK_ENVIRONMENTS || []).find(e => e.id === envId) || { name: 'Consultório' }
  );
  const [info, setInfo]       = useStateP({ name: '', dob: '', cpf: '' });
  const [files, setFiles]     = useStateP([]);
  const [consent, setConsent] = useStateP(false);
  const [submitted, setSubmitted] = useStateP(false);
  const [sending, setSending] = useStateP(false);
  const [sendError, setSendError] = useStateP(null);
  const [showGuide, setShowGuide] = useStateP(false);
  const [showPrivacy, setShowPrivacy] = useStateP(false);
  const [envError, setEnvError] = useStateP(false); // link inválido/expirado

  const pdfRef = useRefP(null);
  const galRef = useRefP(null);
  const camRef = useRefP(null);

  useEffectP(() => {
    if (!window.API || !envId) return;
    window.API.patient.getEnv(envId)
      .then(data => { setEnv(data); setEnvError(false); })
      .catch(() => setEnvError(true)); // link inválido/expirado ou ambiente removido
  }, [envId]);

  const MAX_FILE_BYTES = 20 * 1024 * 1024; // 20 MB por arquivo (limite real do Blob)

  const handleFiles = useCallbackP(async (fileList) => {
    const newFiles = await Promise.all(Array.from(fileList).map(async (file) => {
      const compressed = await compressImage(file);
      const quality = await analyzeImageQuality(compressed);
      const tooBig = compressed.size > MAX_FILE_BYTES;
      const wasCompressed = compressed !== file;
      return {
        id: Math.random().toString(36).slice(2),
        name: compressed.name,
        size: compressed.size,
        isImage: compressed.type.startsWith('image/'),
        preview: compressed.type.startsWith('image/') ? URL.createObjectURL(compressed) : null,
        warnings: tooBig
          ? [...quality.warnings, 'Arquivo acima de 20 MB — remova-o para poder enviar.']
          : quality.warnings,
        wasCompressed,
        tooBig,
        file: compressed,
      };
    }));
    setFiles(prev => [...prev, ...newFiles]);
  }, []);

  const removeFile = (id) => setFiles(prev => prev.filter(f => f.id !== id));

  const hasTooBig = files.some(f => f.tooBig);
  const canSend = files.length > 0 && consent && !sending && !hasTooBig;

  // ─── Envio (reutilizado pelo botão principal e pelo "Tentar novamente") ──────
  const doSubmit = useCallbackP(async () => {
    if (!window.API) { setSubmitted(true); return; }
    setSending(true); setSendError(null);
    try {
      // Converte DD/MM/AAAA → YYYY-MM-DD para o backend
      let dob;
      if (info.dob && info.dob.length === 10) {
        const [d, m, y] = info.dob.split('/');
        dob = `${y}-${m}-${d}`;
      }
      await window.API.patient.submit({
        env_id: envId || '',
        patient_name: info.name || 'Paciente',
        patient_dob: dob,
        patient_cpf: info.cpf || undefined,
        files,
      });
      setSubmitted(true);
    } catch (err) {
      const msgs = {
        'network':      'Sem conexão estável. Seus arquivos continuam selecionados — toque em "Tentar novamente".',
        'invalid-link': 'Este link de envio é inválido ou expirou. Peça um novo link ao seu médico.',
        'too-large':    'Algum arquivo é grande demais (máximo 20 MB). Remova-o e tente novamente.',
        'server':       'Tivemos um problema ao processar o envio. Tente novamente em instantes.',
      };
      setSendError(msgs[err && err.kind] || 'Não foi possível enviar. Tente novamente.');
    } finally {
      setSending(false);
    }
  }, [envId, info, files]);

  const inputStyle = {
    width:'100%', padding:'12px 14px', borderRadius:10,
    border:'1.5px solid #DDD8CE', fontSize:14, color:C.text,
    background:'#F5F0E8', boxSizing:'border-box', outline:'none', transition:'border-color 0.15s',
  };

  // ─── Tela de sucesso ────────────────────────────────────────────────────────
  if (submitted) {
    return (
      <div style={{minHeight:'100vh',background:C.cream,display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',padding:'40px 20px',fontFamily:'DM Sans, sans-serif'}}>
        <div style={{width:80,height:80,borderRadius:'50%',background:C.mid,display:'flex',alignItems:'center',justifyContent:'center',marginBottom:24,boxShadow:'0 12px 32px rgba(44,74,53,0.28)'}}>
          <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5"><polyline points="20 6 9 17 4 12"/></svg>
        </div>
        <h2 style={{fontSize:24,fontWeight:700,color:C.text,marginBottom:8,textAlign:'center',fontFamily:'Lora, serif'}}>Exames enviados!</h2>
        <p style={{fontSize:14,color:C.muted,textAlign:'center',maxWidth:300,lineHeight:1.7,marginBottom:8}}>
          Seus documentos foram recebidos. Em instantes o médico responsável poderá visualizá-los.
        </p>
        <p style={{fontSize:12,color:C.muted,textAlign:'center',maxWidth:300,lineHeight:1.6,marginBottom:32}}>
          Você pode fechar esta página.
        </p>
        <button onClick={() => { setFiles([]); setConsent(false); setSubmitted(false); }}
          style={{padding:'12px 28px',borderRadius:12,border:`1.5px solid ${C.border}`,background:C.white,color:C.mid,fontWeight:600,fontSize:14,cursor:'pointer',fontFamily:'inherit'}}>
          Enviar mais documentos
        </button>
      </div>
    );
  }

  // ─── Tela de link inválido ──────────────────────────────────────────────────
  if (envError) {
    return (
      <div style={{minHeight:'100vh',background:C.cream,display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',padding:'40px 24px',fontFamily:'DM Sans, sans-serif'}}>
        <div style={{width:80,height:80,borderRadius:'50%',background:C.redBg,border:`2px solid ${C.redBorder}`,display:'flex',alignItems:'center',justifyContent:'center',marginBottom:24}}>
          <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke={C.red} strokeWidth="2.2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
        </div>
        <h2 style={{fontSize:22,fontWeight:700,color:C.text,marginBottom:10,textAlign:'center',fontFamily:'Lora, serif'}}>Link inválido ou expirado</h2>
        <p style={{fontSize:14,color:C.muted,textAlign:'center',maxWidth:320,lineHeight:1.7}}>
          Não foi possível abrir este ambiente de envio. Peça ao seu médico um <strong>novo link</strong> e tente novamente.
        </p>
      </div>
    );
  }

  // ─── Modal de política de privacidade ───────────────────────────────────────
  const PrivacyModal = () => (
    <div style={{position:'fixed',inset:0,background:'rgba(0,0,0,0.6)',zIndex:1000,display:'flex',alignItems:'center',justifyContent:'center',padding:16}}
      onClick={e => { if (e.target === e.currentTarget) setShowPrivacy(false); }}>
      <div style={{background:C.white,borderRadius:20,padding:'28px 24px',maxWidth:480,width:'100%',maxHeight:'80vh',overflowY:'auto',boxShadow:'0 20px 60px rgba(0,0,0,0.2)'}}>
        <h3 style={{fontSize:17,fontWeight:700,color:C.text,margin:'0 0 16px',fontFamily:'Lora, serif'}}>Política de Privacidade</h3>
        {[
          ['Quem somos', `Este formulário é operado pelo profissional de saúde responsável por ${env.name}. Ele é o controlador dos dados coletados.`],
          ['O que coletamos', 'Coletamos seu nome, data de nascimento, CPF (opcional) e os documentos de exames que você enviar.'],
          ['Para que usamos', 'Os dados são usados exclusivamente para análise clínica pelo profissional responsável por este ambiente.'],
          ['Por quanto tempo', 'Seus dados são armazenados por até 5 anos ou pelo prazo mínimo exigido pelo CFM, após o que são excluídos.'],
          ['Seus direitos (LGPD)', 'Você pode solicitar acesso, correção ou exclusão dos seus dados a qualquer momento. Entre em contato com o profissional responsável ou envie e-mail para o endereço informado no rodapé.'],
          ['Compartilhamento', 'Seus dados não são vendidos ou compartilhados com terceiros para fins comerciais.'],
          ['Segurança', 'Os dados são transmitidos via HTTPS e armazenados em servidores seguros com controle de acesso.'],
        ].map(([title, text]) => (
          <div key={title} style={{marginBottom:16}}>
            <div style={{fontSize:12,fontWeight:700,color:C.subtext,textTransform:'uppercase',letterSpacing:'0.06em',marginBottom:4}}>{title}</div>
            <div style={{fontSize:13,color:C.text,lineHeight:1.65}}>{text}</div>
          </div>
        ))}
        <button onClick={() => setShowPrivacy(false)}
          style={{width:'100%',padding:'13px',borderRadius:12,border:'none',background:C.mid,color:C.white,fontSize:14,fontWeight:700,cursor:'pointer',fontFamily:'inherit',marginTop:8}}>
          Fechar
        </button>
      </div>
    </div>
  );

  return (
    <div style={{minHeight:'100vh',background:C.cream,fontFamily:'DM Sans, sans-serif'}}>
      {showGuide && (
        <CameraGuideModal
          onClose={() => setShowGuide(false)}
          onCapture={() => { setShowGuide(false); setTimeout(() => camRef.current?.click(), 100); }}
        />
      )}
      {showPrivacy && <PrivacyModal />}

      {/* Header */}
      <header style={{background:`linear-gradient(160deg, ${C.dark} 0%, ${C.mid} 60%, ${C.light} 100%)`,padding:'32px 20px 36px',position:'relative',overflow:'hidden'}}>
        <div style={{position:'absolute',top:-40,right:-40,width:160,height:160,borderRadius:'50%',background:'rgba(92,138,110,0.12)',pointerEvents:'none'}}/>
        <div style={{position:'absolute',bottom:-20,left:-20,width:100,height:100,borderRadius:'50%',background:'rgba(92,138,110,0.08)',pointerEvents:'none'}}/>
        <div style={{maxWidth:480,margin:'0 auto',textAlign:'center',position:'relative'}}>
          <div style={{display:'inline-flex',alignItems:'center',gap:7,marginBottom:12,background:'rgba(255,255,255,0.08)',borderRadius:20,padding:'5px 14px',border:'1px solid rgba(255,255,255,0.1)'}}>
            <div style={{width:6,height:6,borderRadius:'50%',background:'#7AAD8A'}}/>
            <span style={{fontSize:11,fontWeight:600,color:'#A8CDB5',letterSpacing:'0.1em',textTransform:'uppercase'}}>Envio de Exames</span>
          </div>
          <h1 style={{fontSize:24,fontWeight:700,color:'#fff',margin:0,lineHeight:1.3,fontFamily:'Lora, serif'}}>{env.name}</h1>
          <p style={{fontSize:13,color:'rgba(255,255,255,0.45)',margin:'8px 0 0',lineHeight:1.5}}>
            Envie seus exames de forma simples e segura
          </p>
        </div>
      </header>

      <div style={{maxWidth:480,margin:'0 auto',padding:'24px 16px 56px'}}>

        {/* Dados do paciente */}
        <div style={{background:C.white,borderRadius:16,border:`1px solid ${C.border}`,padding:'22px',marginBottom:14,boxShadow:'0 2px 8px rgba(30,51,38,0.05)'}}>
          <div style={{marginBottom:18}}>
            <h3 style={{fontSize:12,fontWeight:700,color:C.subtext,margin:0,textTransform:'uppercase',letterSpacing:'0.08em'}}>Seus dados</h3>
          </div>
          <div style={{display:'flex',flexDirection:'column',gap:14}}>
            <div>
              <label style={{display:'block',fontSize:12,fontWeight:600,color:C.subtext,marginBottom:6}}>Nome completo</label>
              <input style={inputStyle} type="text" placeholder="Maria da Silva"
                value={info.name} onChange={e => setInfo({...info,name:e.target.value})}
                onFocus={e => e.target.style.borderColor=C.sage}
                onBlur={e => e.target.style.borderColor='#DDD8CE'}
              />
            </div>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12}}>
              <div>
                <label style={{display:'block',fontSize:12,fontWeight:600,color:C.subtext,marginBottom:6}}>Nascimento</label>
                <input style={{...inputStyle,fontSize:13}} type="text" placeholder="DD/MM/AAAA"
                  value={info.dob} inputMode="numeric"
                  onChange={e => {
                    let v = e.target.value.replace(/\D/g, '').slice(0, 8);
                    if (v.length > 4) v = v.slice(0,2) + '/' + v.slice(2,4) + '/' + v.slice(4);
                    else if (v.length > 2) v = v.slice(0,2) + '/' + v.slice(2);
                    setInfo({...info, dob: v});
                  }}
                  onFocus={e => e.target.style.borderColor=C.sage}
                  onBlur={e => e.target.style.borderColor='#DDD8CE'}
                />
              </div>
              <div>
                <label style={{display:'block',fontSize:12,fontWeight:600,color:C.subtext,marginBottom:6}}>CPF</label>
                <input style={inputStyle} type="text" placeholder="000.000.000-00"
                  value={info.cpf} inputMode="numeric" maxLength={14}
                  onChange={e => {
                    let v = e.target.value.replace(/\D/g, '').slice(0, 11);
                    if (v.length > 9) v = v.slice(0,3) + '.' + v.slice(3,6) + '.' + v.slice(6,9) + '-' + v.slice(9);
                    else if (v.length > 6) v = v.slice(0,3) + '.' + v.slice(3,6) + '.' + v.slice(6);
                    else if (v.length > 3) v = v.slice(0,3) + '.' + v.slice(3);
                    setInfo({...info, cpf: v});
                  }}
                  onFocus={e => e.target.style.borderColor=C.sage}
                  onBlur={e => e.target.style.borderColor='#DDD8CE'}
                />
              </div>
            </div>
          </div>
        </div>

        {/* Anexar documentos */}
        <div style={{background:C.white,borderRadius:16,border:`1px solid ${C.border}`,padding:'22px',marginBottom:14,boxShadow:'0 2px 8px rgba(30,51,38,0.05)'}}>
          <h3 style={{fontSize:12,fontWeight:700,color:C.subtext,margin:'0 0 4px',textTransform:'uppercase',letterSpacing:'0.08em'}}>Anexar documentos</h3>
          <p style={{fontSize:12,color:C.muted,margin:'0 0 18px'}}>PDF, JPG ou PNG — máximo 20 MB por arquivo</p>
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:10}}>

            {/* PDF */}
            <button onClick={() => pdfRef.current.click()}
              style={{display:'flex',flexDirection:'column',alignItems:'center',gap:10,padding:'20px 8px',borderRadius:14,border:`1.5px solid ${C.border}`,background:C.cream,cursor:'pointer',transition:'all 0.15s',fontFamily:'inherit'}}
              onMouseEnter={e=>{e.currentTarget.style.borderColor=C.sage;e.currentTarget.style.background='#EAF2ED';}}
              onMouseLeave={e=>{e.currentTarget.style.borderColor=C.border;e.currentTarget.style.background=C.cream;}}>
              <div style={{width:46,height:46,borderRadius:12,background:'#FFF0F0',display:'flex',alignItems:'center',justifyContent:'center'}}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#B84040" strokeWidth="1.5">
                  <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                  <polyline points="14 2 14 8 20 8"/>
                  <line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/>
                </svg>
              </div>
              <span style={{fontSize:11,fontWeight:600,color:C.subtext,textAlign:'center',lineHeight:1.3}}>Arquivo<br/>PDF</span>
            </button>

            {/* Galeria */}
            <button onClick={() => galRef.current.click()}
              style={{display:'flex',flexDirection:'column',alignItems:'center',gap:10,padding:'20px 8px',borderRadius:14,border:`1.5px solid ${C.border}`,background:C.cream,cursor:'pointer',transition:'all 0.15s',fontFamily:'inherit'}}
              onMouseEnter={e=>{e.currentTarget.style.borderColor=C.sage;e.currentTarget.style.background='#EAF2ED';}}
              onMouseLeave={e=>{e.currentTarget.style.borderColor=C.border;e.currentTarget.style.background=C.cream;}}>
              <div style={{width:46,height:46,borderRadius:12,background:'#EAF2ED',display:'flex',alignItems:'center',justifyContent:'center'}}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={C.mid} strokeWidth="1.5">
                  <rect x="3" y="3" width="18" height="18" rx="2"/>
                  <circle cx="8.5" cy="8.5" r="1.5"/>
                  <polyline points="21 15 16 10 5 21"/>
                </svg>
              </div>
              <span style={{fontSize:11,fontWeight:600,color:C.subtext,textAlign:'center',lineHeight:1.3}}>Foto da<br/>galeria</span>
            </button>

            {/* Câmera — abre o guia primeiro */}
            <button onClick={() => setShowGuide(true)}
              style={{display:'flex',flexDirection:'column',alignItems:'center',gap:10,padding:'20px 8px',borderRadius:14,border:`1.5px solid ${C.border}`,background:C.cream,cursor:'pointer',transition:'all 0.15s',fontFamily:'inherit'}}
              onMouseEnter={e=>{e.currentTarget.style.borderColor=C.sage;e.currentTarget.style.background='#EAF2ED';}}
              onMouseLeave={e=>{e.currentTarget.style.borderColor=C.border;e.currentTarget.style.background=C.cream;}}>
              <div style={{width:46,height:46,borderRadius:12,background:C.amberBg,display:'flex',alignItems:'center',justifyContent:'center'}}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={C.amber} strokeWidth="1.5">
                  <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
                  <circle cx="12" cy="13" r="4"/>
                </svg>
              </div>
              <span style={{fontSize:11,fontWeight:600,color:C.subtext,textAlign:'center',lineHeight:1.3}}>Tirar<br/>foto</span>
            </button>
          </div>

          <input ref={pdfRef} type="file" accept=".pdf,application/pdf" multiple style={{display:'none'}} onChange={e=>{handleFiles(e.target.files);e.target.value='';}} />
          <input ref={galRef} type="file" accept="image/*" multiple style={{display:'none'}} onChange={e=>{handleFiles(e.target.files);e.target.value='';}} />
          <input ref={camRef} type="file" accept="image/*" capture="environment" style={{display:'none'}} onChange={e=>{handleFiles(e.target.files);e.target.value='';}} />
        </div>

        {/* Lista de arquivos selecionados */}
        {files.length > 0 && (
          <div style={{background:C.white,borderRadius:16,border:`1px solid ${C.border}`,padding:'22px',marginBottom:14,boxShadow:'0 2px 8px rgba(30,51,38,0.05)'}}>
            <h3 style={{fontSize:12,fontWeight:700,color:C.subtext,margin:'0 0 14px',textTransform:'uppercase',letterSpacing:'0.08em'}}>
              Selecionados <span style={{color:C.muted,fontWeight:500,textTransform:'none',letterSpacing:'normal'}}>({files.length})</span>
            </h3>
            <div style={{display:'flex',flexDirection:'column',gap:8}}>
              {files.map(f => (
                <div key={f.id}>
                  <div style={{display:'flex',alignItems:'center',gap:12,padding:'10px 12px',borderRadius:12,background:C.cream,border:`1px solid ${C.border}`}}>
                    <div style={{width:40,height:40,borderRadius:10,background:f.isImage?'#EAF2ED':'#FFF0F0',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0,overflow:'hidden'}}>
                      {f.preview
                        ? <img src={f.preview} style={{width:'100%',height:'100%',objectFit:'cover'}} alt=""/>
                        : <span style={{fontSize:10,fontWeight:800,color:C.red}}>PDF</span>
                      }
                    </div>
                    <div style={{flex:1,minWidth:0}}>
                      <div style={{fontSize:13,fontWeight:600,color:C.text,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{f.name}</div>
                      <div style={{fontSize:11,color:C.muted,marginTop:2}}>{formatBytes(f.size)}</div>
                    </div>
                    <button onClick={() => removeFile(f.id)}
                      style={{width:28,height:28,borderRadius:'50%',border:'none',background:C.border,color:C.muted,cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0,transition:'all 0.15s'}}
                      onMouseEnter={e=>{e.currentTarget.style.background='#FFE0E0';e.currentTarget.style.color=C.red;}}
                      onMouseLeave={e=>{e.currentTarget.style.background=C.border;e.currentTarget.style.color=C.muted;}}>
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                    </button>
                  </div>
                  {/* Aviso de compressão automática */}
                  {f.wasCompressed && (
                    <div style={{display:'flex',alignItems:'flex-start',gap:8,marginTop:6,padding:'8px 12px',borderRadius:8,background:'#F0F7F2',border:`1px solid #C2DBC9`}}>
                      <span style={{fontSize:14,flexShrink:0}}>✓</span>
                      <span style={{fontSize:11,color:'#2C4A35',lineHeight:1.5}}>Foto otimizada automaticamente para envio — qualidade preservada.</span>
                    </div>
                  )}
                  {/* Avisos de qualidade */}
                  {f.warnings && f.warnings.length > 0 && f.warnings.map((w, i) => (
                    <div key={i} style={{display:'flex',alignItems:'flex-start',gap:8,marginTop:6,padding:'8px 12px',borderRadius:8,background:C.amberBg,border:`1px solid #E8D5A0`}}>
                      <span style={{fontSize:14,flexShrink:0}}>⚠️</span>
                      <span style={{fontSize:11,color:'#6B4F10',lineHeight:1.5}}>{w}</span>
                    </div>
                  ))}
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Consentimento LGPD — obrigatório (C1) */}
        <div style={{background:C.white,borderRadius:16,border:`1.5px solid ${consent ? C.sage : C.border}`,padding:'18px 20px',marginBottom:14,boxShadow:'0 2px 8px rgba(30,51,38,0.05)',transition:'border-color 0.2s'}}>
          <label style={{display:'flex',alignItems:'flex-start',gap:12,cursor:'pointer'}}>
            <input
              type="checkbox"
              checked={consent}
              onChange={e => setConsent(e.target.checked)}
              style={{marginTop:2,flexShrink:0,width:18,height:18,accentColor:C.mid,cursor:'pointer'}}
            />
            <div>
              <span style={{fontSize:13,color:C.text,lineHeight:1.65,display:'block'}}>
                Autorizo o envio e armazenamento dos meus dados e documentos de saúde para análise
                pelo profissional responsável por este ambiente. Os dados serão retidos por até
                {' '}<strong>5 anos</strong> e posso solicitar a exclusão a qualquer momento.
              </span>
              <button onClick={e => { e.preventDefault(); setShowPrivacy(true); }}
                style={{marginTop:6,fontSize:12,color:C.sage,background:'none',border:'none',cursor:'pointer',padding:0,fontFamily:'inherit',textDecoration:'underline'}}>
                Ver política de privacidade completa
              </button>
            </div>
          </label>
        </div>

        {/* Botão enviar */}
        <button
          disabled={!canSend}
          onClick={doSubmit}
          style={{
            width:'100%', padding:'16px', borderRadius:14, border:'none',
            background: canSend ? C.mid : '#DDD8CE',
            color: canSend ? '#fff' : C.muted,
            fontSize:15, fontWeight:700,
            cursor: canSend ? 'pointer' : 'not-allowed',
            boxShadow: canSend ? '0 6px 20px rgba(44,74,53,0.28)' : 'none',
            transition:'all 0.2s', fontFamily:'inherit', letterSpacing:'0.01em',
          }}
          onMouseEnter={e=>{ if(canSend){e.currentTarget.style.background=C.dark;e.currentTarget.style.boxShadow='0 8px 24px rgba(44,74,53,0.36)';} }}
          onMouseLeave={e=>{ if(canSend){e.currentTarget.style.background=C.mid;e.currentTarget.style.boxShadow='0 6px 20px rgba(44,74,53,0.28)';} }}
        >
          {sending ? 'Enviando...' : files.length > 0 ? `Enviar ${files.length} arquivo${files.length>1?'s':''}` : 'Enviar exames'}
        </button>

        {!consent && files.length > 0 && (
          <p style={{textAlign:'center',fontSize:12,color:C.muted,marginTop:10}}>
            Marque a caixa de consentimento acima para continuar
          </p>
        )}
        {files.length === 0 && (
          <p style={{textAlign:'center',fontSize:12,color:C.muted,marginTop:10}}>
            Selecione ao menos um arquivo para continuar
          </p>
        )}
        {sendError && (
          <div style={{marginTop:10}}>
            <p style={{textAlign:'center',fontSize:12.5,color:C.red,margin:0,background:C.redBg,padding:'12px 14px',borderRadius:10,border:`1px solid ${C.redBorder}`,lineHeight:1.55}}>{sendError}</p>
            <button
              disabled={!canSend}
              onClick={doSubmit}
              style={{width:'100%',marginTop:10,padding:'13px',borderRadius:12,border:`1.5px solid ${C.mid}`,background:C.white,color:C.mid,fontSize:14,fontWeight:700,cursor:canSend?'pointer':'not-allowed',opacity:canSend?1:0.6,fontFamily:'inherit'}}>
              {sending ? 'Enviando...' : 'Tentar novamente'}
            </button>
          </div>
        )}

        {/* Rodapé LGPD (A7) */}
        <div style={{marginTop:32,paddingTop:20,borderTop:`1px solid ${C.border}`,textAlign:'center'}}>
          <p style={{fontSize:11,color:C.muted,lineHeight:1.7,margin:0}}>
            Seus dados são protegidos pela{' '}
            <strong style={{color:C.subtext}}>LGPD (Lei 13.709/2018)</strong>.
            Dúvidas sobre privacidade?{' '}
            <button onClick={() => setShowPrivacy(true)}
              style={{fontSize:11,color:C.sage,background:'none',border:'none',cursor:'pointer',padding:0,fontFamily:'inherit',textDecoration:'underline'}}>
              Saiba mais
            </button>
          </p>
        </div>

      </div>
    </div>
  );
};

Object.assign(window, { PatientArea });
