/* global React, Card, Badge, Button, Avatar, Icon, ICONS, Field, sb */
const { useState: useStateNP, useEffect: useEffectNP } = React;

/**
 * Converte string de valor monetário BR ou US para float.
 * Exemplos suportados:
 *   "1.500,00"  → 1500.00  (BR com separador de milhar)
 *   "1500,50"   → 1500.50  (BR decimal)
 *   "1500.50"   → 1500.50  (US decimal)
 *   "1.500"     → 1500     (BR milhar sem centavos)
 *   "R$ 2.000"  → 2000
 *   "5000"      → 5000
 */
function parseBRCurrency(str) {
  if (!str) return null;
  // Remove símbolo, espaços e letras (ex: "R$")
  let s = str.replace(/[^\d.,]/g, '').trim();
  if (!s) return null;
  if (s.includes('.') && s.includes(',')) {
    // Formato BR: 1.500,00 → remover pontos de milhar, trocar vírgula por ponto
    s = s.replace(/\./g, '').replace(',', '.');
  } else if (s.includes(',')) {
    // Só vírgula → separador decimal BR: 1500,50 → 1500.50
    s = s.replace(',', '.');
  }
  // Se só ponto ou só dígitos: deixa como está (ex: 1500.50, 1500, 1.500)
  // Caso especial: único ponto mas parece separador de milhar (ex: "1.500" → 3 dígitos após ponto)
  const dotIdx = s.indexOf('.');
  if (dotIdx !== -1 && (s.length - dotIdx - 1) === 3 && !s.includes(',')) {
    // Provavelmente separador de milhar sem centavos (ex: "1.500")
    s = s.replace('.', '');
  }
  const val = parseFloat(s);
  return isNaN(val) ? null : val;
}

function NewProject({ onClose, onCreate }) {
  const [step,     setStep]     = useStateNP(0);
  const [name,     setName]     = useStateNP('');
  const [client,   setClient]   = useStateNP('');
  const [tpl,      setTpl]      = useStateNP(0);
  const [budget,   setBudget]   = useStateNP('');
  const [deadline, setDeadline] = useStateNP('');
  const [saving,        setSaving]        = useStateNP(false);
  const [clients,       setClients]       = useStateNP([]);
  const [newClientName, setNewClientName] = useStateNP('');
  const [addingClient,  setAddingClient]  = useStateNP(false);
  const [currentUser,   setCurrentUser]   = useStateNP(null);
  const [inviteEmail,   setInviteEmail]   = useStateNP('');
  const [invites,       setInvites]       = useStateNP([]);

  useEffectNP(() => {
    sb.from('clients').select('id, name').order('name').then(({ data }) => {
      setClients((data || []).map(c => c.name).filter(Boolean));
    });
    (async () => {
      const { data: { user } } = await sb.auth.getUser();
      if (!user) return;
      const { data: profile } = await sb.from('profiles').select('name, studio, avatar_url').eq('id', user.id).single();
      setCurrentUser({
        id:     user.id,
        name:   profile?.name || user.email?.split('@')[0] || 'Você',
        role:   profile?.studio || 'Proprietário',
        avatar: profile?.avatar_url || null,
      });
    })();
  }, []);

  const templates = [
    { t:'Branding completo',     d:'Briefing → Conceito → Identidade → Manual',  n:'14 etapas', c:'linear-gradient(135deg,#1D39C4,#36CFC9)' },
    { t:'Site / Landing',        d:'Briefing → Wireframe → UI → Dev → QA',        n:'12 etapas', c:'linear-gradient(135deg,#FA541C,#FADB14)' },
    { t:'Campanha de lançamento',d:'Estratégia → Conteúdo → Mídia → Relatório',  n:'10 etapas', c:'linear-gradient(135deg,#7C3AED,#1D39C4)' },
    { t:'Em branco',             d:'Comece do zero, monte seu próprio fluxo',    n:'0 etapas',  c:'linear-gradient(135deg,#475569,#64748B)' },
  ];
  const steps = ['Modelo','Detalhes','Equipe','Revisão'];
  const canNext = [
    true,
    name.trim().length > 1 && client.length > 0,
    true,
    true,
  ][step];

  async function handleCreate() {
    setSaving(true);
    try {
      const { data: { user } } = await sb.auth.getUser();
      const rawBudget = parseBRCurrency(budget);
      const { data, error } = await sb.from('projects').insert({
        user_id:     user.id,
        name:        name.trim(),
        client:      client === '+ novo cliente' ? '' : client,
        status:      'andamento',
        progress:    0,
        budget:      rawBudget,
        deadline:    deadline || null,
        gradient:    templates[tpl].c,
        description: templates[tpl].t,
      }).select().single();
      if (error) { window.__toast?.(error.message, { tone: 'danger' }); setSaving(false); return; }
      onCreate?.({ name: data.name, client: data.client || '', id: data.id, deadline: data.deadline, budget: data.budget });
    } catch (e) {
      window.__toast?.('Erro ao criar projeto', { tone: 'danger' });
      setSaving(false);
    }
  }

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(7,11,28,0.72)', backdropFilter: 'blur(6px)',
      display: 'grid', placeItems: 'center', zIndex: 9999, padding: 24,
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 'min(880px, 100%)', maxHeight: '90vh', display: 'flex', flexDirection: 'column',
        background: 'var(--bg-surface)', border: '1px solid var(--border-strong)',
        borderRadius: 18, boxShadow: '0 30px 80px rgba(0,0,0,0.55)', overflow: 'hidden',
      }}>
        {/* Header */}
        <div style={{ padding: '22px 26px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--geek-blue-300)' }}>Novo projeto</div>
            <h2 style={{ margin: '4px 0 0', fontSize: 20, fontWeight: 700 }}>{['Escolha um modelo','Detalhes do projeto','Convide a equipe','Confira e crie'][step]}</h2>
          </div>
          <button onClick={onClose} style={{ background: 'transparent', border: '1px solid var(--border-subtle)', color: 'var(--fg-secondary)', width: 36, height: 36, borderRadius: 8, cursor: 'pointer', fontSize: 18 }}>×</button>
        </div>

        {/* Stepper */}
        <div style={{ display: 'flex', gap: 0, padding: '14px 26px', borderBottom: '1px solid var(--border-subtle)', background: 'var(--bg-elevated)' }}>
          {steps.map((s, i) => (
            <div key={s} style={{ display: 'flex', alignItems: 'center', gap: 10, flex: 1 }}>
              <div style={{
                width: 26, height: 26, borderRadius: 999, fontSize: 12, fontWeight: 700,
                display: 'grid', placeItems: 'center',
                background: i <= step ? 'var(--primary)' : 'var(--bg-surface)',
                color: i <= step ? '#fff' : 'var(--fg-muted)',
                border: '1px solid', borderColor: i <= step ? 'var(--primary)' : 'var(--border-subtle)',
              }}>{i < step ? '✓' : i + 1}</div>
              <span style={{ fontSize: 12, fontWeight: 600, color: i <= step ? 'var(--fg-primary)' : 'var(--fg-muted)' }}>{s}</span>
              {i < steps.length - 1 && <div style={{ flex: 1, height: 1, background: i < step ? 'var(--primary)' : 'var(--border-subtle)', margin: '0 12px' }}/>}
            </div>
          ))}
        </div>

        {/* Body */}
        <div style={{ padding: '24px 26px', overflow: 'auto', flex: 1 }}>
          {step === 0 && (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              {templates.map((tp, i) => (
                <div key={i} onClick={() => setTpl(i)} style={{
                  cursor: 'pointer', padding: 0, borderRadius: 14, overflow: 'hidden',
                  border: '1.5px solid', borderColor: tpl === i ? 'var(--primary)' : 'var(--border-subtle)',
                  background: 'var(--bg-elevated)', transition: 'all 180ms',
                  boxShadow: tpl === i ? '0 0 0 4px var(--primary-soft)' : 'none',
                }}>
                  <div style={{ height: 64, background: tp.c }}/>
                  <div style={{ padding: 14 }}>
                    <div style={{ fontSize: 14, fontWeight: 700 }}>{tp.t}</div>
                    <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 4 }}>{tp.d}</div>
                    <div style={{ fontSize: 11, color: 'var(--geek-blue-300)', marginTop: 8, fontFamily: 'var(--font-mono)' }}>{tp.n}</div>
                  </div>
                </div>
              ))}
            </div>
          )}

          {step === 1 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <Field label="Nome do projeto" placeholder="Ex.: Rebranding Aurora" value={name} onChange={e => setName(e.target.value)}/>
              <div>
                <span style={{ fontFamily: 'var(--font-display)', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--fg-muted)', display: 'block', marginBottom: 8 }}>Cliente</span>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {clients.length === 0 && !addingClient && (
                    <span style={{ fontSize: 12, color: 'var(--fg-muted)' }}>Nenhum cliente cadastrado ainda.</span>
                  )}
                  {clients.map(c => (
                    <button key={c} onClick={() => { setClient(c); setAddingClient(false); }} style={{
                      padding: '8px 14px', borderRadius: 999, fontSize: 12, fontWeight: 600,
                      cursor: 'pointer', fontFamily: 'inherit',
                      background: client === c ? 'var(--primary-soft)' : 'var(--bg-elevated)',
                      color: client === c ? 'var(--geek-blue-200)' : 'var(--fg-secondary)',
                      border: '1px solid', borderColor: client === c ? 'var(--geek-blue-a40)' : 'var(--border-subtle)',
                    }}>{c}</button>
                  ))}
                  {!addingClient && (
                    <button onClick={() => { setAddingClient(true); setClient(''); }} style={{
                      padding: '8px 14px', borderRadius: 999, fontSize: 12, fontWeight: 600,
                      cursor: 'pointer', fontFamily: 'inherit',
                      background: 'var(--bg-elevated)', color: 'var(--geek-blue-300)',
                      border: '1px dashed var(--geek-blue-a40)',
                    }}>+ novo cliente</button>
                  )}
                  {addingClient && (
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', marginTop: 4 }}>
                      <input
                        autoFocus
                        value={newClientName}
                        onChange={e => setNewClientName(e.target.value)}
                        placeholder="Nome do cliente"
                        style={{ flex: 1, padding: '8px 12px', borderRadius: 8, border: '1px solid var(--border-strong)', background: 'var(--bg-elevated)', color: 'var(--fg-primary)', fontSize: 13, fontFamily: 'inherit', outline: 'none' }}
                        onKeyDown={async e => {
                          if (e.key === 'Enter' && newClientName.trim()) {
                            const name = newClientName.trim();
                            const { data: { user } } = await sb.auth.getUser();
                            const { data: row } = await sb.from('clients').insert({ user_id: user.id, name }).select('name').single();
                            if (row) {
                              setClients(prev => [...prev, row.name].sort());
                              setClient(row.name);
                            }
                            setAddingClient(false);
                            setNewClientName('');
                          }
                          if (e.key === 'Escape') { setAddingClient(false); setNewClientName(''); }
                        }}
                      />
                      <button
                        onClick={async () => {
                          if (!newClientName.trim()) return;
                          const name = newClientName.trim();
                          const { data: { user } } = await sb.auth.getUser();
                          const { data: row } = await sb.from('clients').insert({ user_id: user.id, name }).select('name').single();
                          if (row) {
                            setClients(prev => [...prev, row.name].sort());
                            setClient(row.name);
                          }
                          setAddingClient(false);
                          setNewClientName('');
                        }}
                        style={{ padding: '8px 14px', borderRadius: 8, background: 'var(--primary)', color: '#fff', border: 'none', cursor: 'pointer', fontSize: 12, fontWeight: 600, fontFamily: 'inherit' }}
                      >Adicionar</button>
                      <button onClick={() => { setAddingClient(false); setNewClientName(''); }} style={{ background: 'transparent', border: 'none', color: 'var(--fg-muted)', cursor: 'pointer', fontSize: 12 }}>Cancelar</button>
                    </div>
                  )}
                </div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                <Field icon="dollar" label="Orçamento" placeholder="R$ 0,00" value={budget} onChange={e => setBudget(e.target.value)}/>
                <Field icon="cal" label="Prazo" type="date" placeholder="dd/mm/aaaa" value={deadline} onChange={e => setDeadline(e.target.value)}/>
              </div>
            </div>
          )}

          {step === 2 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {/* Current user — always owner, not removable */}
              {currentUser && (
                <div style={{
                  display: 'flex', alignItems: 'center', gap: 12, padding: 14, borderRadius: 10,
                  background: 'var(--primary-soft)', border: '1px solid var(--geek-blue-a40)',
                }}>
                  <Avatar name={currentUser.name} size={38} src={currentUser.avatar}/>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>{currentUser.name}</div>
                    <div style={{ fontSize: 11, color: 'var(--fg-muted)' }}>{currentUser.role} · Proprietário</div>
                  </div>
                  <div style={{
                    width: 20, height: 20, borderRadius: 6,
                    background: 'var(--primary)', border: '1.5px solid var(--primary)',
                    color: '#fff', display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 700,
                  }}>✓</div>
                </div>
              )}

              {/* Invited people */}
              {invites.map((email, i) => (
                <div key={email} style={{
                  display: 'flex', alignItems: 'center', gap: 12, padding: 14, borderRadius: 10,
                  background: 'var(--bg-elevated)', border: '1px solid var(--border-subtle)',
                }}>
                  <Avatar name={email} size={38} idx={i + 1}/>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>{email}</div>
                    <div style={{ fontSize: 11, color: 'var(--fg-muted)' }}>Convite pendente</div>
                  </div>
                  <button onClick={() => setInvites(inv => inv.filter(e => e !== email))} style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', fontSize:18, lineHeight:1, padding:4 }}>×</button>
                </div>
              ))}

              {/* Invite field */}
              <div style={{ display:'flex', gap:8, marginTop:4 }}>
                <input
                  type="email"
                  value={inviteEmail}
                  onChange={e => setInviteEmail(e.target.value)}
                  placeholder="E-mail do colaborador"
                  style={{ flex:1, padding:'9px 12px', borderRadius:8, border:'1px solid var(--border-strong)', background:'var(--bg-elevated)', color:'var(--fg-primary)', fontSize:13, fontFamily:'inherit', outline:'none' }}
                  onKeyDown={e => {
                    if (e.key === 'Enter' && inviteEmail.trim()) {
                      setInvites(inv => [...inv, inviteEmail.trim()]);
                      setInviteEmail('');
                    }
                  }}
                />
                <button
                  onClick={() => { if (inviteEmail.trim()) { setInvites(inv => [...inv, inviteEmail.trim()]); setInviteEmail(''); } }}
                  style={{ padding:'9px 16px', borderRadius:8, background:'var(--bg-elevated)', border:'1px solid var(--border-strong)', color:'var(--fg-secondary)', cursor:'pointer', fontSize:13, fontWeight:600, fontFamily:'inherit' }}
                >Convidar</button>
              </div>
              <p style={{ margin:0, fontSize:11, color:'var(--fg-muted)' }}>Os convites serão enviados por e-mail após a criação do projeto.</p>
            </div>
          )}

          {step === 3 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <Card padding={16} style={{ background: 'var(--bg-elevated)' }}>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 10, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--fg-muted)' }}>Resumo</div>
                <div style={{ marginTop: 10, display: 'grid', gridTemplateColumns: '140px 1fr', rowGap: 10, fontSize: 13 }}>
                  <span style={{ color: 'var(--fg-muted)' }}>Modelo</span><span style={{ fontWeight: 600 }}>{templates[tpl].t}</span>
                  <span style={{ color: 'var(--fg-muted)' }}>Nome</span><span style={{ fontWeight: 600 }}>{name || '—'}</span>
                  <span style={{ color: 'var(--fg-muted)' }}>Cliente</span><span style={{ fontWeight: 600 }}>{client || '—'}</span>
                  <span style={{ color: 'var(--fg-muted)' }}>Orçamento</span><span style={{ fontFamily: 'var(--font-mono)' }}>{budget || '—'}</span>
                  <span style={{ color: 'var(--fg-muted)' }}>Prazo</span><span style={{ fontFamily: 'var(--font-mono)' }}>{deadline || '—'}</span>
                  <span style={{ color: 'var(--fg-muted)' }}>Equipe</span>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    {currentUser && <Avatar name={currentUser.name} size={26} src={currentUser.avatar}/>}
                    {invites.map((email, i) => <Avatar key={email} name={email} size={26} idx={i+1}/>)}
                    <span style={{ fontSize:11, color:'var(--fg-muted)' }}>{1 + invites.length} {1 + invites.length === 1 ? 'pessoa' : 'pessoas'}</span>
                  </div>
                </div>
              </Card>
              <div style={{ display: 'flex', gap: 10 }}>
                <Badge tone="brand" dot={false}>Briefing será criado</Badge>
                <Badge tone="cyan" dot={false}>Pasta de arquivos</Badge>
                <Badge tone="success" dot={false}>Canal de mensagens</Badge>
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div style={{ padding: '16px 26px', borderTop: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontSize: 12, color: 'var(--fg-muted)' }}>Etapa {step + 1} de {steps.length}</span>
          <div style={{ flex: 1 }}/>
          {step > 0 && <Button variant="secondary" onClick={() => setStep(step - 1)}>Voltar</Button>}
          {step < steps.length - 1 ? (
            <Button onClick={() => canNext && setStep(step + 1)} style={{ opacity: canNext ? 1 : 0.5, pointerEvents: canNext ? 'auto' : 'none' }}>Continuar →</Button>
          ) : (
            <Button onClick={handleCreate} icon="check" style={{ opacity: saving ? 0.6 : 1, pointerEvents: saving ? 'none' : 'auto' }}>
              {saving ? 'Criando…' : 'Criar projeto'}
            </Button>
          )}
        </div>
      </div>
    </div>
  );
}
window.NewProject = NewProject;
