/* educator-styletailor.jsx — "Style Tailor": type a website, re-skin the platform */

function StyleTailor() {
  const [url, setUrl] = useState("");
  const [phase, setPhase] = useState("idle");   // idle | scanning | result
  const [step, setStep] = useState(0);
  const [result, setResult] = useState(null);
  const [applied, setApplied] = useState(() => (window.VHTheme && window.VHTheme.current()) || null);
  const [saved, setSaved] = useState(() => (window.VHTheme && window.VHTheme.savedList()) || []);

  const SCAN_STEPS = [
    ["Fetching site", "globe"],
    ["Extracting colour palette", "star"],
    ["Detecting typography", "file"],
    ["Building platform theme", "wand"],
  ];

  function toast(m, i) { if (window.eduToast) window.eduToast(m, i); }

  /* Real run: kick off the live extraction (curated → /api/brand → generated)
     and advance the visible scan steps while that network request is in flight,
     holding on the last step until the brand data actually lands. */
  async function run(seed) {
    const target = (seed != null ? seed : url).trim();
    if (!target) return;
    if (seed != null) setUrl(seed);
    setPhase("scanning"); setStep(0); setResult(null);
    let i = 0;
    const timer = setInterval(() => { i = Math.min(i + 1, SCAN_STEPS.length - 1); setStep(i); }, 480);
    let theme;
    try { theme = await window.VHTheme.analyzeAsync(target); }
    catch (e) { theme = window.VHTheme.generated(target); }
    clearInterval(timer);
    setStep(SCAN_STEPS.length);   // all steps complete
    setResult(theme); setPhase("result");
  }

  function applyTheme() {
    window.VHTheme.apply(result, true);
    setApplied(result);
    toast(`Platform restyled to match ${result.name}`, "wand");
  }
  function resetTheme() {
    window.VHTheme.reset();
    setApplied(null); setResult(null); setPhase("idle"); setUrl("");
    toast("Reset to Van Haren default", "refresh");
  }
  function saveExample(t) {
    if (!t) return;
    setSaved(window.VHTheme.savePreset(t));
    toast(`Saved ${t.name} to your brand library`, "star");
  }
  function removeSaved(domain, name) {
    setSaved(window.VHTheme.removePreset(domain));
    toast(`Removed ${name} from library`, "x");
  }
  const isSaved = d => saved.some(s => s.domain === d);

  /* Van Haren partner academies — the default examples. */
  const PARTNERS = [
    { domain:"capgemini.com",       label:"Capgemini Academy" },
    { domain:"startel.nl",          label:"Startel" },
    { domain:"globalknowledge.com", label:"Global Knowledge" },
    { domain:"nyenrode.nl",         label:"Nyenrode" },
    { domain:"icm.nl",              label:"ICM" },
  ];

  function favicon(domain) { return `https://www.google.com/s2/favicons?domain=${domain}&sz=64`; }

  return (
    <div>
      <div className="page-head"><h1>Style Tailor</h1><p>Type any website and instantly re-skin the entire platform — colours and typography — to match that brand.</p></div>

      {/* Input card */}
      <div className="card" style={{ padding:24, marginBottom:18, background:"linear-gradient(135deg, color-mix(in oklab,var(--vh-blue-500),transparent 94%), transparent 60%)" }}>
        <div style={{ display:"flex", gap:12, flexWrap:"wrap" }}>
          <label className="search" style={{ flex:1, minWidth:260, maxWidth:"none", padding:"14px 16px", background:"var(--surface)", border:"1.5px solid var(--line)" }}>
            <Icon name="globe" size={19} style={{ color:"var(--ink-3)" }}/>
            <input value={url} onChange={e=>setUrl(e.target.value)} onKeyDown={e=>{ if(e.key==="Enter") run(); }}
              placeholder="e.g. spotify.com" style={{ fontSize:15.5 }}/>
          </label>
          <button className="btn btn-pri" style={{ padding:"0 26px", fontSize:15 }} onClick={()=>run()} disabled={phase==="scanning"}>
            <Icon name="wand" size={17}/>{phase==="scanning" ? "Tailoring…" : "Tailor platform"}
          </button>
        </div>
        <div style={{ display:"flex", alignItems:"center", gap:9, marginTop:14, flexWrap:"wrap" }}>
          <span className="dim" style={{ fontSize:12, fontWeight:700, textTransform:"uppercase", letterSpacing:".1em" }}>Partner academies</span>
          {PARTNERS.map(p=>(
            <button key={p.domain} className="filter-chip" onClick={()=>run(p.domain)} style={{ display:"inline-flex", alignItems:"center", gap:7 }}>
              <img src={favicon(p.domain)} alt="" width="15" height="15" style={{ borderRadius:3, display:"block" }} onError={e=>e.target.style.display="none"}/>{p.label}
            </button>
          ))}
        </div>
        {saved.length > 0 && (
          <div style={{ display:"flex", alignItems:"center", gap:9, marginTop:11, flexWrap:"wrap" }}>
            <span className="dim" style={{ fontSize:12, fontWeight:700, textTransform:"uppercase", letterSpacing:".1em", display:"inline-flex", alignItems:"center", gap:5 }}><Icon name="star" size={13}/>Saved brands</span>
            {saved.map(s=>(
              <span key={s.domain} className="filter-chip" style={{ display:"inline-flex", alignItems:"center", gap:7, paddingRight:5 }}>
                <button onClick={()=>run(s.domain)} style={{ display:"inline-flex", alignItems:"center", gap:7, background:"none", border:"none", padding:0, font:"inherit", color:"inherit", cursor:"pointer" }}>
                  <span style={{ width:15, height:15, borderRadius:4, flex:"none", background:`linear-gradient(135deg, ${s.primary}, ${s.navy})`, display:"grid", placeItems:"center", color:"#fff", fontSize:8, fontWeight:800 }}>{s.mark}</span>{s.name}
                </button>
                <button onClick={()=>removeSaved(s.domain, s.name)} aria-label={"Remove "+s.name} style={{ display:"grid", placeItems:"center", width:18, height:18, borderRadius:5, color:"var(--ink-3)", background:"none", border:"none", cursor:"pointer" }}
                  onMouseEnter={e=>{ e.currentTarget.style.background="var(--surface-3)"; e.currentTarget.style.color="#c62828"; }}
                  onMouseLeave={e=>{ e.currentTarget.style.background="none"; e.currentTarget.style.color="var(--ink-3)"; }}><Icon name="x" size={11}/></button>
              </span>
            ))}
          </div>
        )}
      </div>

      {/* Scanning */}
      {phase==="scanning" && (
        <div className="card" style={{ padding:"26px 24px", marginBottom:18 }}>
          <div style={{ display:"flex", flexDirection:"column", gap:13 }}>
            {SCAN_STEPS.map(([label,ic],i)=>{
              const done = i < step, active = i === step;
              return (
                <div key={label} style={{ display:"flex", alignItems:"center", gap:13, opacity:done||active?1:.4, transition:"opacity .3s" }}>
                  <div style={{ width:32, height:32, borderRadius:9, flex:"none", display:"grid", placeItems:"center",
                    background: done?"var(--vh-blue-50)":active?"color-mix(in oklab,var(--vh-blue-500),transparent 88%)":"var(--surface-3)",
                    color: done||active?"var(--vh-blue-500)":"var(--ink-3)" }}>
                    {done ? <Icon name="check" size={16}/> : <Icon name={ic} size={16} style={active?{ animation:"vhPop .6s ease infinite alternate" }:undefined}/>}
                  </div>
                  <span style={{ fontSize:14.5, fontWeight:600, color: done||active?"var(--ink)":"var(--ink-3)" }}>{label}</span>
                  {active && <div className="bar" style={{ flex:1, maxWidth:160, marginLeft:6 }}><i style={{ width:"60%" }}/></div>}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Result */}
      {phase==="result" && result && (
        <div className="card" style={{ padding:0, marginBottom:18, overflow:"hidden" }}>
          <div style={{ display:"flex", alignItems:"center", gap:16, padding:"20px 24px", borderBottom:"1px solid var(--line)" }}>
            <Mark theme={result} size={54}/>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ display:"flex", alignItems:"center", gap:9 }}>
                <h2 style={{ fontSize:20, fontWeight:800 }}>{result.name}</h2>
                <span className={"tag "+(sourceMeta(result).cls)}>{sourceMeta(result).label}</span>
              </div>
              <div className="dim" style={{ fontSize:13, marginTop:3 }}>
                {result.domain}{result.source === "generated" && " · couldn’t read this site, generated a close palette"}
              </div>
            </div>
            <div style={{ display:"flex", gap:10 }}>
              <button className="btn btn-outline" onClick={()=>{ setPhase("idle"); setResult(null); }}>Cancel</button>
              <button className="btn btn-outline" onClick={()=>saveExample(result)} disabled={isSaved(result.domain)}>
                <Icon name="star" size={15}/>{isSaved(result.domain) ? "Saved" : "Save example"}
              </button>
              <button className="btn btn-pri" onClick={applyTheme}><Icon name="check" size={15}/>Apply to entire platform</button>
            </div>
          </div>

          <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:0 }}>
            {/* Palette + type */}
            <div style={{ padding:"20px 24px", borderRight:"1px solid var(--line)" }}>
              <div className="eyebrow" style={{ marginBottom:12 }}>Extracted palette</div>
              <div style={{ display:"flex", gap:10, marginBottom:20 }}>
                {[["Primary",result.primary],["Dark",result.navy],["Accent",result.accent2]].map(([lbl,c])=>(
                  <div key={lbl} style={{ flex:1 }}>
                    <div style={{ height:54, borderRadius:11, background:c, border:"1px solid rgba(0,0,0,.08)", boxShadow:"var(--shadow-sm)" }}/>
                    <div style={{ fontSize:11.5, fontWeight:700, marginTop:7 }}>{lbl}</div>
                    <div className="dim" style={{ fontSize:11, fontFamily:"ui-monospace,monospace", textTransform:"uppercase" }}>{c}</div>
                  </div>
                ))}
              </div>
              <div className="eyebrow" style={{ marginBottom:10 }}>Typography</div>
              {[["Headings",result.display],["Body",result.body]].map(([lbl,f])=>(
                <div key={lbl} className="between" style={{ padding:"9px 0", borderBottom:"1px solid var(--line-2)" }}>
                  <span className="dim" style={{ fontSize:12.5 }}>{lbl}</span>
                  <span style={{ fontWeight:700, fontSize:15 }}>{f}</span>
                </div>
              ))}
            </div>

            {/* Live preview */}
            <div style={{ padding:"20px 24px", background:"var(--surface-2)" }}>
              <div className="eyebrow" style={{ marginBottom:12 }}>Header takeover</div>
              <BrandLockup theme={result}/>
              <div className="eyebrow" style={{ margin:"18px 0 12px" }}>Live preview</div>
              <ThemePreview theme={result}/>
            </div>
          </div>
        </div>
      )}

      {/* Current theme status */}
      <div className="card" style={{ padding:"16px 22px" }}>
        <div className="between" style={{ gap:16, flexWrap:"wrap" }}>
          <div style={{ display:"flex", alignItems:"center", gap:13 }}>
            {applied ? (
              <>
                <Mark theme={applied} size={40}/>
                <div>
                  <div style={{ fontWeight:700, fontSize:14.5 }}>Active theme · {applied.name}</div>
                  <div className="dim" style={{ fontSize:12.5 }}>Applied across Educator, Trainer & Learner portals</div>
                </div>
              </>
            ) : (
              <>
                <div style={{ width:40, height:40, borderRadius:11, flex:"none", display:"grid", placeItems:"center", background:"var(--vh-blue-50)", color:"var(--vh-blue-500)" }}><Icon name="palette" size={19}/></div>
                <div>
                  <div style={{ fontWeight:700, fontSize:14.5 }}>Van Haren default theme</div>
                  <div className="dim" style={{ fontSize:12.5 }}>No custom brand applied yet</div>
                </div>
              </>
            )}
          </div>
          {applied && (
            <div style={{ display:"flex", gap:10 }}>
              <button className="btn btn-outline" onClick={()=>saveExample(applied)} disabled={isSaved(applied.domain)}><Icon name="star" size={14}/>{isSaved(applied.domain) ? "Saved" : "Save example"}</button>
              <button className="btn btn-outline" onClick={resetTheme}><Icon name="refresh" size={14}/>Reset to Van Haren</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* How the result was resolved — drives the badge wording + colour. */
function sourceMeta(t) {
  if (t.known) return { label:"Brand matched", cls:"green" };
  if (t.source === "brandfetch" || t.source === "scrape") return { label:"Read from site", cls:"green" };
  return { label:"Palette generated", cls:"blue" };
}

/* Brand mark: real logo when we have one, else the coloured monogram tile.
   Falls back to the monogram automatically if the logo image fails to load. */
function Mark({ theme, size }) {
  const [bad, setBad] = useState(false);
  const mono = theme.mark || (window.VHTheme && window.VHTheme.monogram(theme.name)) || "•";
  const fontHead = `'${theme.display}', system-ui, sans-serif`;
  const r = Math.round(size * 0.26);
  if (theme.logo && !bad) {
    return (
      <div style={{ width:size, height:size, borderRadius:r, flex:"none", display:"grid", placeItems:"center", overflow:"hidden", background:"#fff", border:"1px solid var(--line)", boxShadow:"var(--shadow-sm)" }}>
        <img src={theme.logo} alt="" style={{ width:"82%", height:"82%", objectFit:"contain" }} onError={()=>setBad(true)}/>
      </div>
    );
  }
  return (
    <div style={{ width:size, height:size, borderRadius:r, flex:"none", display:"grid", placeItems:"center", background:`linear-gradient(135deg, ${theme.primary}, ${theme.navy})`, color:"#fff", fontFamily:fontHead, fontWeight:800, fontSize:size*(mono.length>=3?0.32:0.42), letterSpacing:"-.02em", boxShadow:"var(--shadow-sm)" }}>{mono}</div>
  );
}

function BrandLockup({ theme }) {
  const fontHead = `'${theme.display}', system-ui, sans-serif`;
  return (
    <div style={{ display:"flex", alignItems:"center", gap:12, padding:"14px 16px", background:"#fff", border:"1px solid var(--line)", borderRadius:14, boxShadow:"var(--shadow-sm)" }}>
      <Mark theme={theme} size={38}/>
      <div style={{ lineHeight:1.1, minWidth:0 }}>
        <div style={{ fontFamily:fontHead, fontWeight:800, fontSize:17, color:theme.navy, letterSpacing:"-.01em", whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis" }}>{theme.name}</div>
        <div style={{ fontSize:10, fontWeight:700, letterSpacing:".18em", textTransform:"uppercase", color:"var(--ink-3)", marginTop:3 }}>Educator</div>
      </div>
    </div>
  );
}

function ThemePreview({ theme }) {
  const p = theme.primary, navy = theme.navy, soft = `color-mix(in oklab, ${p}, #fff 90%)`;
  const fontBody = `'${theme.body}', system-ui, sans-serif`, fontHead = `'${theme.display}', system-ui, sans-serif`;
  return (
    <div style={{ borderRadius:14, overflow:"hidden", border:"1px solid var(--line)", background:"#fff", fontFamily:fontBody, display:"flex", boxShadow:"var(--shadow-sm)" }}>
      {/* mini sidebar */}
      <div style={{ width:72, background:"#fff", borderRight:"1px solid var(--line)", padding:"12px 8px", display:"flex", flexDirection:"column", gap:6 }}>
        <div style={{ width:26, height:26, borderRadius:8, background:`linear-gradient(135deg, ${p}, ${navy})`, margin:"0 auto 8px", display:"grid", placeItems:"center", color:"#fff", fontFamily:fontHead, fontWeight:800, fontSize:(theme.mark&&theme.mark.length>=3?8:10), letterSpacing:"-.02em" }}>{theme.mark || ""}</div>
        {[0,1,2].map(i=>(
          <div key={i} style={{ display:"flex", alignItems:"center", gap:6, padding:"7px 6px", borderRadius:8, background:i===0?soft:"transparent" }}>
            <div style={{ width:14, height:14, borderRadius:4, background:i===0?p:"var(--line)" }}/>
            <div style={{ height:5, flex:1, borderRadius:3, background:i===0?p:"var(--surface-3)", opacity:i===0?1:.7 }}/>
          </div>
        ))}
      </div>
      {/* mini body */}
      <div style={{ flex:1, padding:"14px 15px" }}>
        <div style={{ fontFamily:fontHead, fontWeight:800, fontSize:17, color:navy, letterSpacing:"-.01em" }}>Good morning</div>
        <div style={{ height:6, width:"55%", borderRadius:4, background:"var(--surface-3)", margin:"9px 0 14px" }}/>
        <div style={{ display:"flex", gap:8, marginBottom:13 }}>
          <span style={{ background:p, color:"#fff", fontWeight:700, fontSize:12, padding:"8px 14px", borderRadius:9 }}>Primary</span>
          <span style={{ background:soft, color:navy, fontWeight:700, fontSize:12, padding:"8px 14px", borderRadius:9 }}>Soft</span>
          <span style={{ background:theme.accent2, color:"#fff", fontWeight:700, fontSize:12, padding:"8px 14px", borderRadius:9 }}>Accent</span>
        </div>
        <div style={{ border:"1px solid var(--line)", borderRadius:11, padding:12 }}>
          <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:9 }}>
            <div style={{ height:6, width:70, borderRadius:4, background:"var(--surface-3)" }}/>
            <span style={{ fontSize:11, fontWeight:800, color:p, background:soft, padding:"3px 9px", borderRadius:999 }}>XP</span>
          </div>
          <div style={{ height:8, borderRadius:999, background:"var(--surface-3)", overflow:"hidden" }}>
            <div style={{ width:"68%", height:"100%", borderRadius:999, background:`linear-gradient(90deg, ${theme.accent2}, ${p})` }}/>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { StyleTailor, BrandLockup, Mark });
