// Editor.jsx — Premium lyric editor

const MOCK_LYRICS = [
  { id: 's1', type: 'Verso 1', lines: ['Antes que yo hablara,', 'Antes que pensara,', 'Tú me amaste.', 'Antes que fallara,', 'O Te entregara mi corazón,'] },
  { id: 's2', type: 'Pre-coro', lines: ['Tú me amaste,', 'Sí, me amaste.'] },
  { id: 's3', type: 'Coro', lines: ['Oh, el increíble, generoso amor de Dios', 'Como una avalancha, barre mi alma', 'Y cuando no Te merecía, aún así me amaste'] },
  { id: 's4', type: 'Verso 2', lines: ['Cuando era enemigo,', 'Fuiste mi abrigo,', 'Sin juzgar.'] },
  { id: 's5', type: 'Puente', lines: ['No hay montaña que no escales por mí', 'No hay muralla que no derribes por mí'] },
];

function SectionTag({ type }) {
  const c = {
    'Coro': { bg: 'rgba(244,114,182,0.18)', fg: '#F472B6' },
    'Puente': { bg: 'rgba(96,165,250,0.18)', fg: '#60A5FA' },
    'Verso 1': { bg: 'rgba(192,132,252,0.18)', fg: '#C084FC' },
    'Verso 2': { bg: 'rgba(192,132,252,0.18)', fg: '#C084FC' },
    'Pre-coro': { bg: 'rgba(251,191,36,0.16)', fg: '#FBBF24' },
    'Final': { bg: 'rgba(52,211,153,0.16)', fg: '#34D399' },
  };
  const s = c[type] || { bg: 'rgba(255,255,255,0.08)', fg: '#fff' };
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', padding: '5px 11px',
      borderRadius: 8, background: s.bg, color: s.fg,
      fontSize: 10, fontWeight: 600,
      fontFamily: 'var(--hl-font-mono)', letterSpacing: 1,
      textTransform: 'uppercase',
    }}>{type}</span>
  );
}

function EditorScreen({ song, onBack, onSend, fontSize = 16 }) {
  // Prefer real parsed sections from /acordes (set by api-mock.jsx parser).
  // Fall back to MOCK_LYRICS only when nothing came through.
  const [sections, setSections] = React.useState(
    Array.isArray(song?.sections) && song.sections.length > 0
      ? song.sections
      : MOCK_LYRICS
  );

  const updateLine = (sIdx, lIdx, v) => {
    const next = [...sections];
    next[sIdx] = { ...next[sIdx], lines: [...next[sIdx].lines] };
    next[sIdx].lines[lIdx] = v;
    setSections(next);
  };
  const addLine = (sIdx) => {
    const next = [...sections];
    next[sIdx] = { ...next[sIdx], lines: [...next[sIdx].lines, ''] };
    setSections(next);
  };
  const removeLine = (sIdx, lIdx) => {
    const next = [...sections];
    next[sIdx] = { ...next[sIdx], lines: next[sIdx].lines.filter((_, i) => i !== lIdx) };
    setSections(next);
  };

  return (
    <div style={{
      height: '100%',
      background: 'linear-gradient(180deg, #0E0726 0%, #08051A 100%)',
      display: 'flex', flexDirection: 'column', position: 'relative',
    }}>
      <div style={{ height: 'calc(var(--safe-top, 44px) + 14px)', flexShrink: 0 }} />

      <div style={{
        padding: '10px 20px 14px',
        borderBottom: '1px solid rgba(255,255,255,0.06)',
        display: 'flex', alignItems: 'center', gap: 12,
        background: 'rgba(14,7,38,0.85)',
        backdropFilter: 'blur(24px)', WebkitBackdropFilter: 'blur(24px)',
        position: 'relative', zIndex: 5,
      }}>
        <button onClick={onBack} style={{
          width: 38, height: 38, borderRadius: 12,
          background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.08)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer', flexShrink: 0,
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M9 2L3 7l6 5" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontFamily: 'var(--hl-font-display)', fontSize: 19, fontWeight: 400, fontStyle: 'italic',
            color: '#fff', letterSpacing: -0.4, lineHeight: 1.15,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{song?.name || song?.title || 'Reckless Love'}</div>
          <div style={{
            fontSize: 11, color: 'rgba(255,255,255,0.5)', marginTop: 2,
            display: 'flex', alignItems: 'center', gap: 6,
            fontFamily: 'var(--hl-font-mono)', letterSpacing: 0.4,
          }}>
            <div style={{ width: 5, height: 5, borderRadius: '50%', background: '#34D399', boxShadow: '0 0 6px #34D399' }} />
            <span>{song?.artist?.name || song?.artist || 'Cory Asbury'} · auto-guardando</span>
          </div>
        </div>
      </div>

      <div className="hl-stagger" style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden', padding: '16px 20px 130px' }}>
        {sections.map((sec, sIdx) => (
          <div key={sec.id} style={{ marginBottom: 22 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <SectionTag type={sec.type} />
              <div style={{
                fontSize: 10, color: 'rgba(255,255,255,0.35)',
                fontFamily: 'var(--hl-font-mono)', letterSpacing: 0.6,
              }}>{sec.lines.length} líneas</div>
            </div>
            <div style={{
              background: 'rgba(255,255,255,0.035)',
              backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
              borderRadius: 16, padding: '8px 4px',
              border: '1px solid rgba(255,255,255,0.06)',
            }}>
              {sec.lines.map((line, lIdx) => (
                <div key={lIdx} style={{
                  display: 'flex', alignItems: 'flex-start', gap: 8,
                  padding: '4px 8px',
                }}>
                  <div style={{
                    width: 18, paddingTop: 8, fontSize: 9,
                    color: 'rgba(255,255,255,0.25)', textAlign: 'right',
                    fontFamily: 'var(--hl-font-mono)', flexShrink: 0,
                  }}>{lIdx + 1}</div>
                  <input value={line} onChange={e => updateLine(sIdx, lIdx, e.target.value)}
                    style={{
                      flex: 1, background: 'transparent', border: 'none', outline: 'none',
                      color: '#fff', fontSize: fontSize,
                      fontFamily: 'var(--hl-font-display)', fontStyle: 'italic',
                      letterSpacing: -0.3, padding: '6px 4px', lineHeight: 1.4, fontWeight: 400,
                    }}/>
                  <button onClick={() => removeLine(sIdx, lIdx)} style={{
                    width: 22, height: 22, borderRadius: 6, border: 'none',
                    background: 'transparent',
                    color: 'rgba(255,255,255,0.25)', cursor: 'pointer', fontSize: 14,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    flexShrink: 0,
                  }}>×</button>
                </div>
              ))}
              <button onClick={() => addLine(sIdx)} style={{
                width: '100%', textAlign: 'left', padding: '7px 30px',
                background: 'transparent', border: 'none', cursor: 'pointer',
                color: 'rgba(192,132,252,0.75)', fontSize: 13,
                fontFamily: 'var(--hl-font-ui)', fontWeight: 500,
              }}>+ Añadir línea</button>
            </div>
          </div>
        ))}

        <button style={{
          width: '100%', height: 50, borderRadius: 16,
          background: 'rgba(255,255,255,0.04)',
          border: '1px dashed rgba(255,255,255,0.18)',
          color: 'rgba(255,255,255,0.65)', cursor: 'pointer',
          fontSize: 13, fontWeight: 500, fontFamily: 'var(--hl-font-ui)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          <span style={{ fontSize: 16, lineHeight: 1 }}>+</span> Nueva sección
        </button>
      </div>

      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        padding: '14px 16px calc(30px + var(--safe-bottom, 16px))',
        background: 'linear-gradient(180deg, transparent, rgba(8,5,26,0.95) 30%)',
        zIndex: 10,
      }}>
        <button onClick={onSend} style={{
            width: '100%', height: 56, borderRadius: 18, border: 'none',
            position: 'relative', overflow: 'hidden',
            background: 'linear-gradient(135deg, #B45EFF 0%, #7C3AED 50%, #4F1FCB 100%)',
            color: '#fff', fontSize: 16, fontWeight: 600,
            fontFamily: 'var(--hl-font-ui)', letterSpacing: -0.2, cursor: 'pointer',
            boxShadow: '0 14px 40px rgba(168,85,247,0.5), inset 0 1px 0 rgba(255,255,255,0.25)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
          <div style={{
            position: 'absolute', top: 0, left: 0, right: 0, height: '50%',
            background: 'linear-gradient(180deg, rgba(255,255,255,0.18), transparent)',
            pointerEvents: 'none',
          }} />
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" style={{ position: 'relative' }}>
            <path d="M2 8l5-5v3h7v4H7v3L2 8z" fill="white" transform="rotate(-90 8 8)"/>
          </svg>
          <span style={{ position: 'relative' }}>Enviar a HolyLyrics</span>
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { EditorScreen, MOCK_LYRICS, SectionTag });
