// UploadGate — first screen the user sees when entering the app.
// Asks them to "upload" 3 taxonomy books with specific names. The files are
// validated only by filename pattern, NEVER read or stored. Once all 3 are
// recognized, we simulate analysis for ~3s, then unlock the app.

const { useState, useRef, useEffect } = React;

const SLOTS = [
  {
    id: 'dx',
    title: 'Taxonomía de diagnósticos',
    hint: 'El archivo debe llamarse "taxonomía nanda"',
    match: /(taxonom[ií]a[\s_-]*nanda|^nanda)/i,
    tone: 'dx',
  },
  {
    id: 'ob',
    title: 'Taxonomía de objetivos',
    hint: 'El archivo debe llamarse "taxonomía noc"',
    match: /(taxonom[ií]a[\s_-]*noc|^noc)/i,
    tone: 'ob',
  },
  {
    id: 'iv',
    title: 'Taxonomía de intervenciones',
    hint: 'El archivo debe llamarse "taxonomía nic"',
    match: /(taxonom[ií]a[\s_-]*nic|^nic)/i,
    tone: 'iv',
  },
];

const UploadSlot = ({ slot, state, onAccept, onReject }) => {
  const inputRef = useRef(null);
  const [dragOver, setDragOver] = useState(false);

  const handleFile = (file) => {
    if (!file) return;
    // We NEVER read the contents. Filename match is the only check.
    if (slot.match.test(file.name)) {
      onAccept(slot.id, file.name);
    } else {
      onReject(slot.id, `"${file.name}" no coincide con el nombre esperado.`);
    }
    // Discard the file reference immediately.
  };

  const onDrop = (e) => {
    e.preventDefault();
    setDragOver(false);
    const f = e.dataTransfer.files?.[0];
    handleFile(f);
  };

  return (
    <div className={`gate-slot tone-${slot.tone} ${dragOver ? 'over' : ''} ${state.status}`}>
      <div className="gate-slot-head">
        <div className={`gate-slot-dot tone-${slot.tone}`}/>
        <div className="gate-slot-title">{slot.title}</div>
      </div>

      {state.status === 'accepted' ? (
        <div className="gate-slot-drop done">
          <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M5 13l4 4L19 7"/>
          </svg>
          <div className="gate-slot-filename">{state.filename}</div>
          <div className="gate-slot-status">Listo · validado</div>
        </div>
      ) : (
        <label
          className={`gate-slot-drop ${state.status === 'error' ? 'err' : ''}`}
          onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
          onDragLeave={() => setDragOver(false)}
          onDrop={onDrop}
        >
          <input
            ref={inputRef}
            type="file"
            style={{ display: 'none' }}
            onChange={(e) => handleFile(e.target.files?.[0])}
          />
          <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
            <path d="M17 8l-5-5-5 5"/>
            <path d="M12 3v12"/>
          </svg>
          <div className="gate-slot-cta">Arrastra tu libro aquí o haz clic</div>
          <div className="gate-slot-hint">{slot.hint}</div>
          {state.status === 'error' && (
            <div className="gate-slot-err">{state.error}</div>
          )}
        </label>
      )}
    </div>
  );
};

const GATE_KEY = 'cynamoonurs_books_uploaded';
const isGateAlreadyPassed = () => {
  try { return localStorage.getItem(GATE_KEY) === '1'; } catch { return false; }
};
const markGatePassed = () => {
  try { localStorage.setItem(GATE_KEY, '1'); } catch {}
};
const resetGate = () => {
  try { localStorage.removeItem(GATE_KEY); } catch {}
};

const UploadGate = ({ onUnlock }) => {
  const [slots, setSlots] = useState({
    dx: { status: 'idle' },
    ob: { status: 'idle' },
    iv: { status: 'idle' },
  });
  const [analyzing, setAnalyzing] = useState(false);
  const [progress, setProgress] = useState(0);
  const [analyzeStep, setAnalyzeStep] = useState(0);

  // If gate has been passed in a previous session, skip directly.
  useEffect(() => {
    if (isGateAlreadyPassed()) {
      loadAllData().then(() => onUnlock());
    }
  }, []);

  const accept = (id, filename) => {
    setSlots(s => ({ ...s, [id]: { status: 'accepted', filename } }));
  };
  const reject = (id, error) => {
    setSlots(s => ({ ...s, [id]: { status: 'error', error } }));
    // Auto-clear error after 4s
    setTimeout(() => setSlots(s => s[id]?.status === 'error' ? ({ ...s, [id]: { status: 'idle' } }) : s), 4000);
  };

  const allReady = ['dx', 'ob', 'iv'].every(k => slots[k].status === 'accepted');

  // Once all 3 are accepted, auto-start the simulated analysis.
  useEffect(() => {
    if (allReady && !analyzing) {
      setAnalyzing(true);
      // Also kick off the real data load in parallel.
      loadAllData();
    }
  }, [allReady]);

  useEffect(() => {
    if (!analyzing) return;
    const steps = [
      'Validando integridad de los libros…',
      'Indexando diagnósticos de enfermería…',
      'Indexando objetivos de enfermería…',
      'Indexando intervenciones de enfermería…',
      'Cruzando relaciones entre taxonomías…',
      'Eliminando los archivos del dispositivo…',
      'Todo listo.',
    ];
    let p = 0;
    let s = 0;
    const id = setInterval(() => {
      p = Math.min(100, p + 4 + Math.random() * 5);
      setProgress(p);
      const nextStep = Math.min(steps.length - 1, Math.floor((p / 100) * steps.length));
      if (nextStep !== s) {
        s = nextStep;
        setAnalyzeStep(s);
      }
      if (p >= 100) {
        clearInterval(id);
        markGatePassed();
        setTimeout(() => onUnlock(), 700);
      }
    }, 180);
    return () => clearInterval(id);
  }, [analyzing]);

  const totalAccepted = ['dx', 'ob', 'iv'].filter(k => slots[k].status === 'accepted').length;

  return (
    <div className="gate" data-screen-label="App — Pantalla de carga">
      <div className="gate-bg"/>
      <div className="gate-shell">
        <header className="gate-head">
          <div className="gate-brand">
            <img src={MASCOT} alt=""/>
            <div>
              <div className="gate-brand-name">Cyna<em>mon</em>urs</div>
              <div className="gate-brand-sub">Compañera de planes de cuidado</div>
            </div>
          </div>
          <div className="gate-step">{analyzing ? 'Paso 2 de 2 · Analizando' : `Paso 1 de 2 · ${totalAccepted}/3 libros`}</div>
        </header>

        {!analyzing ? (
          <>
            <div className="gate-hero">
              <h1>Sube los libros aquí para poder empezar a organizar tu información.</h1>
              <p>
                Cynamonurs es un organizador local: no almacenamos contenido de las taxonomías.
                Sube los tres libros de referencia en cualquier formato. Solo validamos el nombre del archivo
                como llave de acceso; el contenido no se guarda y los archivos se eliminan de inmediato.
              </p>
            </div>

            <div className="gate-grid">
              {SLOTS.map(s => (
                <UploadSlot
                  key={s.id}
                  slot={s}
                  state={slots[s.id]}
                  onAccept={accept}
                  onReject={reject}
                />
              ))}
            </div>

            <footer className="gate-foot">
              <div className="gate-foot-note">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="3" y="11" width="18" height="11" rx="2"/>
                  <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
                </svg>
                Tus archivos nunca salen de tu dispositivo. No se leen ni se conservan.
              </div>
              <div className={'gate-progress-mini ' + (allReady ? 'ready' : '')}>
                <span className={slots.dx.status === 'accepted' ? 'on' : ''}/>
                <span className={slots.ob.status === 'accepted' ? 'on' : ''}/>
                <span className={slots.iv.status === 'accepted' ? 'on' : ''}/>
              </div>
            </footer>
          </>
        ) : (
          <div className="gate-analyzing">
            <div className="gate-analyzing-mascot">
              <img src={MASCOT} alt=""/>
              <div className="gate-mascot-spin"/>
            </div>
            <h2>Estamos preparando tu biblioteca…</h2>
            <p>{[
              'Validando integridad de los libros…',
              'Indexando diagnósticos de enfermería…',
              'Indexando objetivos de enfermería…',
              'Indexando intervenciones de enfermería…',
              'Cruzando relaciones entre taxonomías…',
              'Eliminando los archivos del dispositivo…',
              'Todo listo.'
            ][analyzeStep]}</p>
            <div className="gate-progress">
              <div className="gate-progress-bar" style={{ width: progress + '%' }}/>
            </div>
            <div className="gate-progress-pct mono">{Math.floor(progress)}%</div>
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { UploadGate, resetGate, isGateAlreadyPassed, markGatePassed });
