/* MIRAI — Rastreo IA · componentes de la pantalla
 *
 * Reutiliza piezas del dashboard (DashboardSidebar, Icon, Dropdown, RefreshControl,
 * useToast, ComingSoonNotice, COMING_SOON, miraiFmtTime) y el servicio/datos mock
 * de dashboard-rastreo-data.jsx (searchProperties, RASTREO_*).
 *
 * MVP: sin scraping ni APIs reales. "Iniciar rastreo inteligente" muestra un
 * avance simulado de los pasos de Emma y devuelve propiedades mock.
 */

// ---- Logos de portales inmobiliarios (SVG inline) ----
function PortalLogo({ portalKey, size = 22 }) {
  // Mercado Libre: óvalo amarillo con franja blanca y apretón de manos azul
  if (portalKey === "meli") return (
    <svg width={size} height={size} viewBox="0 0 40 40" fill="none" aria-label="Mercado Libre">
      <rect width="40" height="40" rx="8" fill="#FFE600"/>
      <ellipse cx="20" cy="20" rx="16" ry="12" fill="#FFE600" stroke="#2D3277" strokeWidth="2.2"/>
      <rect x="4" y="15.5" width="32" height="8" fill="#fff"/>
      {/* mano izquierda */}
      <path d="M7 20 C9 17 11.5 18.5 13 17.5 L15.5 19.5 C16 20 16.5 19 17.5 19" stroke="#2D3277" strokeWidth="1.8" strokeLinecap="round" fill="none"/>
      <path d="M13 21.5 C12 23 10 23 8.5 22" stroke="#2D3277" strokeWidth="1.8" strokeLinecap="round" fill="none"/>
      {/* mano derecha */}
      <path d="M33 20 C31 17 28.5 18.5 27 17.5 L24.5 19.5 C24 20 23.5 19 22.5 19" stroke="#2D3277" strokeWidth="1.8" strokeLinecap="round" fill="none"/>
      <path d="M27 21.5 C28 23 30 23 31.5 22" stroke="#2D3277" strokeWidth="1.8" strokeLinecap="round" fill="none"/>
      {/* agarre central */}
      <path d="M17.5 19 C18.5 18 20 18.5 20 19.5 C20 18.5 21.5 18 22.5 19" stroke="#2D3277" strokeWidth="1.8" strokeLinecap="round" fill="none"/>
    </svg>
  );
  // ZonaProp: llave estilizada naranja — círculo arriba, tallo, muescas horizontales
  if (portalKey === "zonaprop") return (
    <svg width={size} height={size} viewBox="0 0 40 40" fill="none" aria-label="ZonaProp">
      <rect width="40" height="40" rx="8" fill="#fff"/>
      {/* cabeza de la llave */}
      <circle cx="22" cy="10" r="6" stroke="#E8401C" strokeWidth="3.2" fill="none"/>
      <circle cx="22" cy="10" r="2" fill="#E8401C"/>
      {/* tallo */}
      <rect x="20" y="15" width="4" height="17" rx="1.5" fill="#E8401C"/>
      {/* muescas */}
      <rect x="20" y="24" width="7" height="3.5" rx="1.5" fill="#E8401C"/>
      <rect x="20" y="28.5" width="5.5" height="3" rx="1.5" fill="#E8401C"/>
    </svg>
  );
  // Argenprop: gradiente verde + "A" estilizada como casa con triángulo interior
  if (portalKey === "argenprop") return (
    <svg width={size} height={size} viewBox="0 0 40 40" fill="none" aria-label="Argenprop">
      <defs>
        <linearGradient id="ap-g" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#1A5C2A"/>
          <stop offset="60%" stopColor="#2D8B3A"/>
          <stop offset="100%" stopColor="#8DC63F"/>
        </linearGradient>
        <clipPath id="ap-clip">
          <rect width="40" height="40" rx="8"/>
        </clipPath>
      </defs>
      <rect width="40" height="40" rx="8" fill="url(#ap-g)"/>
      {/* Diagonal divisoria */}
      <path d="M0 28 L40 14 L40 40 L0 40 Z" fill="#8DC63F" clipPath="url(#ap-clip)"/>
      {/* A / casa: techo (arco) */}
      <path d="M20 7 C20 7 9 18 9 18 L9 33 L16 33 L16 25 L24 25 L24 33 L31 33 L31 18 Z" fill="none" stroke="#fff" strokeWidth="2.8" strokeLinejoin="round"/>
      {/* Triángulo interior (chimenea/tejado) */}
      <path d="M16 18 L20 13 L24 18 Z" fill="#8DC63F"/>
    </svg>
  );
  // Tokko: texto "tokko" en rojo sobre blanco (logo oficial)
  if (portalKey === "tokko") return (
    <svg width={size} height={size} viewBox="0 0 40 40" fill="none" aria-label="Tokko Broker">
      <rect width="40" height="40" rx="8" fill="#fff" stroke="#e8e8e8" strokeWidth="1"/>
      <text x="20" y="25" textAnchor="middle" fontFamily="'Arial Black', Arial, sans-serif" fontWeight="900" fontSize="12" fill="#E03A2E" letterSpacing="-0.5">tokko</text>
    </svg>
  );
  return null;
}

// ---- Select estilado (native, accesible) ----
function RtSelect({ value, options, onChange }) {
  return (
    <div className="dash-rt__selectwrap">
      <select className="dash-rt__select" value={value} onChange={(e) => onChange(e.target.value)}>
        {options.map((o) => <option key={o} value={o}>{o}</option>)}
      </select>
      <span className="dash-rt__selectchev"><Icon name="chevron" size={16} /></span>
    </div>
  );
}

// ---- Campo de chips (con dropdown para agregar) ----
function RtChips({ value, options, onChange, placeholder }) {
  const avail = options.filter((o) => !value.includes(o));
  return (
    <div className="dash-rt__chips">
      {value.map((v) => (
        <span key={v} className="dash-rt__chip">
          {v}
          <button onClick={() => onChange(value.filter((x) => x !== v))} aria-label={`Quitar ${v}`}><Icon name="close" size={12} /></button>
        </span>
      ))}
      {value.length === 0 && placeholder && <span className="dash-rt__chips-ph">{placeholder}</span>}
      <Dropdown
        align="right"
        className="dash-rt__chips-dd"
        button={(open, toggle) => (
          <button className="dash-rt__chips-add" onClick={toggle} aria-label="Agregar"><Icon name="chevron" size={16} /></button>
        )}>
        {avail.length ? avail.map((o) => (
          <button key={o} className="dd__opt" onClick={() => onChange([...value, o])}>{o}</button>
        )) : <div className="dash-rt__dd-empty">Sin más opciones</div>}
      </Dropdown>
    </div>
  );
}

function RtField({ label, children, wide }) {
  return (
    <div className={`dash-rt__field ${wide ? "is-wide" : ""}`}>
      <label className="dash-rt__label">{label}</label>
      {children}
    </div>
  );
}

// ============ FORMULARIO: NUEVA BÚSQUEDA ============
function RastreoForm({ criteria, setCriteria, images, setImages, sources, setSources, onSearch, searching }) {
  const set = (k, v) => setCriteria({ ...criteria, [k]: v });
  const toggleSource = (k) => setSources({ ...sources, [k]: !sources[k] });

  const addImages = (e) => {
    const files = Array.from(e.target.files || []);
    files.forEach((f) => {
      const reader = new FileReader();
      reader.onload = (ev) => setImages((prev) => [...prev, { id: `u${prev.length}-${f.name}`, src: ev.target.result }]);
      reader.readAsDataURL(f);
    });
    e.target.value = "";
  };

  return (
    <section className="dash-card dash-rt__formcard">
      <h3 className="dash-card__title">Nueva búsqueda</h3>

      <div className="dash-rt__grid">
        <RtField label="Cliente">
          <input className="dash-rt__input" value={criteria.cliente} onChange={(e) => set("cliente", e.target.value)} placeholder="Nombre del cliente" />
        </RtField>
        <RtField label="Operación">
          <RtSelect value={criteria.operacion} options={RASTREO_OPERACIONES} onChange={(v) => set("operacion", v)} />
        </RtField>

        <RtField label="Tipo de propiedad">
          <RtSelect value={criteria.tipo} options={RASTREO_TIPOS} onChange={(v) => set("tipo", v)} />
        </RtField>
        <RtField label="Presupuesto">
          <RtSelect value={criteria.presupuesto} options={RASTREO_PRESUPUESTOS} onChange={(v) => set("presupuesto", v)} />
        </RtField>

        <RtField label="Zonas">
          <RtChips value={criteria.zonas} options={RASTREO_ZONAS} onChange={(v) => set("zonas", v)} placeholder="Agregar zonas" />
        </RtField>
        <RtField label="Dormitorios">
          <RtSelect value={criteria.dormitorios} options={RASTREO_DORMITORIOS} onChange={(v) => set("dormitorios", v)} />
        </RtField>

        <RtField label="Ambientes">
          <RtSelect value={criteria.ambientes} options={RASTREO_AMBIENTES} onChange={(v) => set("ambientes", v)} />
        </RtField>
        <RtField label="Superficie mínima">
          <input className="dash-rt__input" value={criteria.superficie} onChange={(e) => set("superficie", e.target.value)} placeholder="Ej: 70 m²" />
        </RtField>

        <RtField label="Características deseadas" wide>
          <RtChips value={criteria.caracteristicas} options={RASTREO_CARACTERISTICAS} onChange={(v) => set("caracteristicas", v)} placeholder="Agregar características" />
        </RtField>

        <RtField label="Observaciones" wide>
          <textarea className="dash-rt__textarea" rows={3} value={criteria.observaciones} onChange={(e) => set("observaciones", e.target.value)} placeholder="Detalles, preferencias, contexto del cliente…" />
        </RtField>
      </div>

      <div className="dash-rt__lower">
        {/* Imágenes de referencia */}
        <div className="dash-rt__lower-col">
          <span className="dash-rt__sublabel">Imágenes de referencia</span>
          <div className="dash-rt__imgs">
            {images.map((im) => (
              <div key={im.id} className="dash-rt__img">
                <img src={im.src} alt="" loading="lazy" />
                <button className="dash-rt__img-x" onClick={() => setImages(images.filter((x) => x.id !== im.id))} aria-label="Quitar imagen"><Icon name="close" size={12} /></button>
              </div>
            ))}
            <label className="dash-rt__addimg">
              <Icon name="plus" size={18} />
              <span>Agregar imagen</span>
              <input type="file" accept="image/*" multiple onChange={addImages} hidden />
            </label>
          </div>
        </div>

        {/* Fuentes a rastrear */}
        <div className="dash-rt__lower-col">
          <span className="dash-rt__sublabel">Fuentes a rastrear <Icon name="info" size={13} /></span>
          <div className="dash-rt__sources">
            {RASTREO_SOURCES.map((s) => (
              <button key={s.key} className={`dash-rt__source ${sources[s.key] ? "is-on" : ""}`} onClick={() => toggleSource(s.key)}>
                <span className="dash-rt__source-logo"><PortalLogo portalKey={s.key} /></span>
                <span className="dash-rt__source-name">{s.label}</span>
                {sources[s.key] && <span className="dash-rt__source-check"><Icon name="check2" size={14} /></span>}
              </button>
            ))}
          </div>
        </div>
      </div>

      <button className="dash-rt__cta" onClick={onSearch} disabled={searching}>
        <Icon name={searching ? "refresh" : "sparkle"} size={18} />
        {searching ? "Rastreando…" : "Iniciar rastreo inteligente"}
      </button>
    </section>
  );
}

// ============ PANEL DERECHO: RESUMEN ============
function RastreoSummary({ criteria }) {
  const rows = [
    ["user", "Cliente", criteria.cliente],
    ["refresh", "Operación", criteria.operacion],
    ["home", "Tipo de propiedad", criteria.tipo],
    ["pin", "Zonas", criteria.zonas.join(", ")],
    ["wallet", "Presupuesto", criteria.presupuesto],
    ["target", "Ambientes", criteria.ambientes],
    ["home", "Dormitorios", criteria.dormitorios],
    ["external", "Superficie mínima", criteria.superficie],
    ["sparkle", "Características", criteria.caracteristicas.join(", ")],
  ];
  return (
    <div className="dash-card dash-rt__summary">
      <h3 className="dash-card__title">Resumen de búsqueda</h3>
      <dl className="dash-rt__summary-list">
        {rows.map(([ic, k, v]) => (
          <div key={k} className="dash-rt__summary-row">
            <span className="dash-rt__summary-ico"><Icon name={ic} size={16} /></span>
            <dt className="dash-rt__summary-k">{k}</dt>
            <dd className="dash-rt__summary-v">{v || "—"}</dd>
          </div>
        ))}
      </dl>
    </div>
  );
}

// ============ PANEL DERECHO: OPCIONES ============
function RastreoOpciones({ opts, setOpts }) {
  return (
    <div className="dash-card dash-rt__emma">
      <h3 className="dash-card__title">Opciones</h3>
      <div className="dash-rt__steps" style={{ gap: 18, marginTop: 16 }}>
        <div className="dash-rt__toggle">
          <span className="dash-rt__toggle-txt">Consultar disponibilidad y validar precio actualizado</span>
          <button role="switch" aria-checked={opts.checkAvail} className={`dash-switch dash-switch--green ${opts.checkAvail ? "is-on" : ""}`} onClick={() => setOpts({ ...opts, checkAvail: !opts.checkAvail })}>
            <span className="dash-switch__knob"></span>
          </button>
        </div>
        <div className="dash-rt__toggle">
          <span className="dash-rt__toggle-txt">Incluir publicaciones similares</span>
          <button role="switch" aria-checked={opts.similar} className={`dash-switch dash-switch--green ${opts.similar ? "is-on" : ""}`} onClick={() => setOpts({ ...opts, similar: !opts.similar })}>
            <span className="dash-switch__knob"></span>
          </button>
        </div>
      </div>
    </div>
  );
}

// ============ RESULTADOS: TARJETA DE PROPIEDAD ============
function PropertyCard({ p, onView, onSend }) {
  const [fav, setFav] = React.useState(false);
  const src = RASTREO_SOURCE_MAP[p.portal] || { label: p.portal, color: "#888", ink: "#fff", short: "?" };
  return (
    <div className="dash-rt__prop">
      <div className="dash-rt__prop-media">
        <img src={p.image} alt={p.title} loading="lazy" />
        <span className="dash-rt__portal" style={{ background: src.color, color: src.ink }}>
          <span className="dash-rt__portal-logo"><PortalLogo portalKey={p.portal} size={16} /></span>{src.label}
        </span>
        <button className={`dash-rt__fav ${fav ? "is-on" : ""}`} onClick={() => setFav((v) => !v)} aria-label="Favorito">
          <Icon name={fav ? "heart-fill" : "heart"} size={17} />
        </button>
      </div>
      <div className="dash-rt__prop-body">
        <h4 className="dash-rt__prop-title">{p.title}</h4>
        <span className="dash-rt__prop-loc"><Icon name="pin" size={14} /> {p.location}</span>
        <span className="dash-rt__prop-price">{p.price}</span>
        <span className="dash-rt__prop-specs">{p.amb} amb. · {p.dorm} dorm. · {p.sup} m²</span>
        <span className="dash-rt__match">{p.match}% coincidencia</span>
        <div className="dash-rt__prop-actions">
          <button className="dash-rt__btn" onClick={() => onView(p)}>Ver publicación <Icon name="external" size={15} /></button>
          <button className="dash-rt__btn" onClick={() => onSend(p)}>Enviar al cliente <Icon name="send" size={15} /></button>
        </div>
      </div>
    </div>
  );
}

// ============ RESULTADOS ============
function RastreoResults({ status, summary, results, onView, onSend }) {
  return (
    <section className="dash-card dash-rt__resultscard">
      <div className="dash-rt__results-head">
        <h3 className="dash-card__title">Propiedades encontradas</h3>
        {status === "done" && summary && (
          <span className="dash-rt__results-status"><Icon name="check2" size={15} /> {summary.label}</span>
        )}
      </div>

      {status === "idle" && (
        <div className="dash-rt__results-empty">
          <span className="dash-rt__results-empty-ico"><Icon name="radar" size={28} /></span>
          <p>Completá la búsqueda e iniciá el rastreo para ver coincidencias.</p>
        </div>
      )}

      {status === "searching" && (
        <div className="dash-rt__results-empty">
          <span className="dash-rt__results-empty-ico is-spin"><Icon name="refresh" size={28} /></span>
          <p>Rastreando portales y comparando coincidencias…</p>
        </div>
      )}

      {status === "done" && (
        <div className="dash-rt__results">
          {results.map((p) => <PropertyCard key={p.id} p={p} onView={onView} onSend={onSend} />)}
        </div>
      )}
    </section>
  );
}

// ============ PÁGINA ============
function RastreoPage({ user, onLogout, env, setEnv, showEnvSwitch }) {
  const [criteria, setCriteria] = React.useState(() => ({
    ...RASTREO_DEFAULT_CRITERIA,
    zonas: [...RASTREO_DEFAULT_CRITERIA.zonas],
    caracteristicas: [...RASTREO_DEFAULT_CRITERIA.caracteristicas],
  }));
  const [images, setImages] = React.useState(() => RASTREO_REF_IMAGES.map((i) => ({ ...i })));
  const [sources, setSources] = React.useState({ meli: true, zonaprop: true, argenprop: true, tokko: true });
  const [opts, setOpts] = React.useState({ checkAvail: true, similar: true });
  const [status, setStatus] = React.useState("idle"); // idle | searching | done
  const [step, setStep] = React.useState(0);
  const [results, setResults] = React.useState([]);
  const [summary, setSummary] = React.useState(null);
  const [sbOpen, setSbOpen] = React.useState(false);
  const [lastUpdated, setLastUpdated] = React.useState(() => new Date());
  const [toast, showToast] = useToast();
  const stepTimer = React.useRef(null);

  React.useEffect(() => () => clearInterval(stepTimer.current), []);

  const onSearch = () => {
    if (status === "searching") return;
    setStatus("searching");
    setResults([]);
    setSummary(null);
    setStep(0);
    clearInterval(stepTimer.current);
    stepTimer.current = setInterval(() => {
      setStep((s) => {
        const next = s + 1;
        if (next >= RASTREO_EMMA_STEPS.length) clearInterval(stepTimer.current);
        return Math.min(next, RASTREO_EMMA_STEPS.length);
      });
    }, 400);
    searchProperties(criteria).then((res) => {
      clearInterval(stepTimer.current);
      setStep(RASTREO_EMMA_STEPS.length);
      setResults(res.properties);
      setSummary(res.summary);
      setStatus("done");
      setLastUpdated(new Date());
    });
  };

  const onView = () => showToast("Abriendo la publicación en el portal…");
  const onSend = (p) => showToast(`Enviado a ${criteria.cliente || "el cliente"}: ${p.title}`);

  return (
    <div className="dboard">
      <DashboardSidebar active="rastreo" user={user} onComingSoon={() => showToast(COMING_SOON)} open={sbOpen} onClose={() => setSbOpen(false)} env={env} setEnv={setEnv} showEnvSwitch={showEnvSwitch} />

      <div className="dash-main">
        <header className="dash-head">
          <div className="dash-head__left">
            <button className="dash-iconbtn dash-head__menu" onClick={() => setSbOpen(true)} aria-label="Abrir menú"><Icon name="menu" /></button>
            <div className="dash-head__heading">
              <h1 className="dash-head__title">Rastreo inteligente de propiedades</h1>
              <p className="dash-head__sub">Cargá lo que busca tu cliente y encontrá coincidencias en múltiples portales</p>
            </div>
          </div>
          <div className="dash-head__right">
            <RefreshControl onRefresh={() => setLastUpdated(new Date())} loading={status === "searching"} lastUpdated={lastUpdated} />
            <Dropdown
              align="right" className="dash-profile"
              button={(open, toggle) => (
                <button className="dash-avatar" onClick={toggle} aria-label="Perfil"><Icon name="user" size={18} /></button>
              )}>
              <button className="dd__opt" onClick={() => showToast(COMING_SOON)}>Mi cuenta</button>
              <button className="dd__opt" onClick={onLogout}>Cerrar sesión</button>
            </Dropdown>
          </div>
        </header>

        <div className="dash-rt__top dash-fade is-in">
          <RastreoForm
            criteria={criteria} setCriteria={setCriteria}
            images={images} setImages={setImages}
            sources={sources} setSources={setSources}
            onSearch={onSearch} searching={status === "searching"} />

          <aside className="dash-rt__side">
            <RastreoSummary criteria={criteria} />
            <RastreoOpciones opts={opts} setOpts={setOpts} />
          </aside>
        </div>

        <RastreoResults status={status} summary={summary} results={results} onView={onView} onSend={onSend} />
      </div>

      <ComingSoonNotice msg={toast} />
    </div>
  );
}

Object.assign(window, { RastreoPage });
