import React, {useEffect,useMemo,useState} from 'react';
import {createRoot} from 'react-dom/client';
import {ShieldCheck,ShieldAlert,Search,ArrowRight,ArrowLeft,CheckCircle2,HelpCircle,LockKeyhole,Smartphone,Clock,ExternalLink,Download,RotateCcw,Info,ChevronDown,BookOpen,Check,Globe2,FileText} from 'lucide-react';
import {normalizeHost,findHosts,assess} from './assessment.js';
import './styles.css';

const choices = {
  visit:[['yes','Yes — on November 16'],['no','No, I don’t think so'],['unsure','I’m not sure']],
  activity:[['browse','I only browsed or read'],['login','I logged into an account'],['card','I entered payment card details'],['crypto','I copied a crypto address or made a transfer']],
  device:[['iphone','iPhone or iPad'],['android','Android phone'],['computer','Computer or other device']]
};
const source='https://report-uri.ghost.io/worlds-largest-brands-infected-with-malware-via-optimizely/';
const browserHelp = {
  safari:{name:'Safari (iPhone)',steps:['Open Safari.','Tap the Bookmarks icon, then the clock-shaped History tab.','Find visits from Monday, November 16, 2026.','Return here and type the exact website address you recognize.']},
  chrome:{name:'Chrome (Android / iPhone)',steps:['Open Chrome.','Open the three-dot menu and choose History.','Look for Monday, November 16, 2026.','Return here and enter any website you want to check.']},
  samsung:{name:'Samsung Internet',steps:['Open Samsung Internet.','Open the menu (three horizontal lines), then History.','Review visits from November 16, 2026.','Return here and enter a relevant website address.']},
  firefox:{name:'Firefox mobile',steps:['Open Firefox and its menu.','Choose History and review November 16, 2026.','Return here to check the addresses you find.']}
};
function Choice({label,options,value,onChange}) {return <div className="field"><div className="fieldlabel">{label}</div><div className="choices">{options.map(([v,text])=><button key={v} type="button" className={'option '+(value===v?'selected':'')} onClick={()=>onChange(v)} aria-pressed={value===v}><span>{text}</span><span className="choice-circle">{value===v&&<Check size={13}/>}</span></button>)}</div></div>}
function App(){
  const [data,setData]=useState(null),[loadError,setLoadError]=useState(false);
  const [step,setStep]=useState(0),[query,setQuery]=useState(''),[selected,setSelected]=useState('');
  const [visit,setVisit]=useState('unsure'),[activity,setActivity]=useState('browse'),[device,setDevice]=useState('android'),[dateTime,setDateTime]=useState('');
  const [browser,setBrowser]=useState('chrome'),[showHelp,setShowHelp]=useState(false),[showList,setShowList]=useState(false);
  useEffect(()=>{fetch('/data/incident.json',{cache:'no-store'}).then(r=>{if(!r.ok)throw Error();return r.json()}).then(setData).catch(()=>setLoadError(true))},[]);
  const organizations=data?.organizations||[];
  const matches=useMemo(()=>{let q=query.trim().toLowerCase();if(q.length<2)return [];return organizations.filter(o=>o.name.toLowerCase().includes(q)||o.domains.some(d=>d.includes(q))).slice(0,12)},[query,organizations]);
  const input=selected||query;const match=useMemo(()=>findHosts(organizations,input),[organizations,input]);
  const valid=normalizeHost(input);
  const result=useMemo(()=>assess({match,visit,activity,device,time:dateTime}),[match,visit,activity,device,dateTime]);
  const reset=()=>{setStep(0);setQuery('');setSelected('');setVisit('unsure');setActivity('browse');setDateTime('');setShowList(false);setDevice('android');setShowHelp(false)};
  const summary=`CyberCheck — Optimizely November 16, 2026\nWebsite: ${match.host||"Invalid hostname"}\nDomain match: ${match.kind}\nReported visit: ${visit}\nActivity: ${activity}\nDevice: ${device}\nResult: ${result.label}\n${result.description}\n\nActions:\n${result.actions.map((a,i)=>`${i+1}. ${a}`).join('\n')}\n\nSource: ${source}\nNot a malware scan or a guarantee of safety.\nGenerated locally on your device.`;
  const download=()=>{const blob=new Blob([summary],{type:'text/plain;charset=utf-8'});const url=URL.createObjectURL(blob);const a=document.createElement('a');a.href=url;a.download='cybercheck-assessment.txt';a.click();URL.revokeObjectURL(url)};
  return <div className="app"><header className="nav"><div className="container navinner"><div className="brand" onClick={reset} role="button" tabIndex={0} onKeyDown={e=>e.key==='Enter'&&reset()}><span className="brandmark"><ShieldCheck size={22}/></span><strong>CyberCheck</strong><span className="branddot">•</span><span className="brandtag">Exposure checker</span></div><a className="navlink" href={source} target="_blank" rel="noreferrer">Original research <ExternalLink size={14}/></a></div></header>
  <main className="container min-h-screen"><div className="hero"><span className="eyebrow"><span className="live-dot"/> VERIFIED INCIDENT · NOV 16, 2026</span><h1>Was your device <em>potentially exposed?</em></h1><p>Check whether a website you visited appears in the Optimizely malware incident research. Get clear, personalized next steps — privately, in about a minute.</p><div className="trust"><span><LockKeyhole size={15}/> No signup</span><span><ShieldCheck size={15}/> Checked on your device</span><span><Clock size={15}/> ~60 seconds</span></div></div>
  <div className="workspace"><section className="panel mainpanel"><div className="steps"><span className={step>=0?'active':''}>1 <span>Check website</span></span><div/><span className={step>=1?'active':''}>2 <span>Activity</span></span><div/><span className={step>=2?'active':''}>3 <span>Results</span></span></div>
  {loadError?<div className="error"><ShieldAlert/> The incident dataset failed to load. Refresh the page; no assessment can be made without it.</div>:!data?<p>Loading verified incident data…</p>:<>
  {step===0&&<div className="stepbody" aria-live="polite"><span className="sectionmark">STEP 01</span><h2>Which website did you visit?</h2><p className="muted">Search by company name, or paste the exact URL from your browser history. Specific hostnames matter.</p><label className="searchbox"><Search size={19}/><input value={query} autoComplete="off" spellCheck="false" onChange={e=>{setQuery(e.target.value);setSelected('')}} placeholder="Try cnn.com, zoom.us, or Equifax" aria-label="Website or company name"/></label>
    {query.length>=2&&<div className="suggestions">{matches.length?matches.map(o=><button type="button" key={o.id} onClick={()=>{setQuery(o.name);setSelected('')}}><strong>{o.name}</strong><span>Choose the exact hostname below</span></button>):<p>No listed company matches that search. This does not establish safety.</p>}</div>}
    {matches.length>0&&!valid&&<div className="hostchoices" aria-label="Published hostnames">{[...new Set(matches.flatMap(o=>o.domains))].map(host=><button className="secondary" type="button" key={host} onClick={()=>{setSelected(host);setQuery(host)}}>{host}</button>)}</div>}
    <div className="matchnotice">{match.kind==='exact'?<><CheckCircle2 size={18}/><span><b>Exact published hostname match</b><small>{match.matches.map(x=>x.name).join(', ')}. This is not proof your visit was affected.</small></span></>:match.kind==='related'?<><Info size={18}/><span><b>Related hostname, not an exact match</b><small>Verify the precise address against the published research.</small></span></>:<><Info size={18}/><span><b>178 organizations in the research</b><small>253 explicitly published hostnames in this curated dataset; some additional hostnames were abbreviated in the source.</small></span></>}</div>
    <button className="textbutton" type="button" onClick={()=>setShowList(!showList)}>{showList?'Hide':'Browse'} all listed organizations <ChevronDown size={16}/></button>
    {showList&&<div className="alllist">{organizations.map(o=><button type="button" key={o.id} onClick={()=>{setQuery(o.name);setSelected('');setShowList(false)}}><b>{o.name}</b><small>{o.domains.join(', ')}</small></button>)}</div>}
    <button className="primary" type="button" disabled={!valid||!selected&&match.kind==='invalid'} onClick={()=>setStep(1)}>Continue <ArrowRight size={18}/></button>
    <div className="helper"><button type="button" onClick={()=>setShowHelp(!showHelp)}><Smartphone size={17}/> Not sure? Find your phone's browser history <ChevronDown size={15}/></button>
    {showHelp&&<div className="helppanel"><label htmlFor="browser">Select your browser</label><select id="browser" value={browser} onChange={e=>setBrowser(e.target.value)}>{Object.entries(browserHelp).map(([id,b])=><option value={id} key={id}>{b.name}</option>)}</select><ol>{browserHelp[browser].steps.map(s=><li key={s}>{s}</li>)}</ol><p>Private or deleted history may not be available. We never access your history automatically.</p></div>}</div></div>}
  {step===1&&<div className="stepbody" aria-live="polite"><span className="sectionmark">STEP 02</span><h2>Tell us about your visit</h2><p className="muted">Answer based on what you remember. It's okay to be unsure.</p><div className="selectedsite"><Globe2 size={18}/><div><small>WEBSITE CHECKED</small><b>{match.host||input}</b></div><span className={'matchpill '+(match.kind==='exact'?'yes':'')}>{match.kind==='exact'?'Listed hostname':'Not confirmed'}</span></div>
    <Choice label="Did you visit this website on November 16, 2026?" options={choices.visit} value={visit} onChange={setVisit}/>
    <Choice label="What did you do?" options={choices.activity} value={activity} onChange={setActivity}/>
    <Choice label="What device did you use?" options={choices.device} value={device} onChange={setDevice}/>
    <div className="field"><label htmlFor="visit-time" className="fieldlabel">Approximate visit time (optional)</label><input id="visit-time" className="datefield" type="datetime-local" value={dateTime} onChange={e=>setDateTime(e.target.value)}/><small className="muted">Uses your device’s local time zone. Broad event observations only; exact per-site timing is not known.</small></div>
    <div className="actions"><button type="button" className="secondary" onClick={()=>setStep(0)}><ArrowLeft size={18}/> Back</button><button type="button" className="primary" onClick={()=>setStep(2)}>View assessment <ArrowRight size={18}/></button></div></div>}
  {step===2&&<div className="stepbody" aria-live="polite"><span className="sectionmark">YOUR ASSESSMENT</span><h2>Here's what we found</h2><div className={'result '+result.level}><div className="resulttop"><span className="resulticon">{result.level==='action'?<ShieldAlert size={24}/>:result.level==='possible'?<Info size={24}/>:<HelpCircle size={24}/>}</span><div><small>{result.level==='action'?'ACTION PRIORITY':result.level==='possible'?'POTENTIAL EXPOSURE':'UNCONFIRMED'}</small><h3>{result.label}</h3></div></div><p>{result.description}</p></div><h3 className="whatnow">What to do next</h3><ul className="checklist">{result.actions.map((a,i)=><li key={i}><span>{i+1}</span>{a}</li>)}</ul><div className="resultnotice"><Info size={19}/> CyberCheck is a screening tool, not a malware detector. Even an exact match does not prove malicious code ran, and an unmatched site is not proof of safety.</div><div className="actions wrap"><button type="button" className="secondary" onClick={()=>setStep(1)}><ArrowLeft size={17}/> Edit answers</button><button type="button" className="secondary" onClick={download}><Download size={17}/> Save summary</button><button type="button" className="primary" onClick={reset}><RotateCcw size={17}/> Check another</button></div></div>}
  </>}</section>
  <aside className="sidebar"><div className="sidecard"><span className="sideicon"><ShieldCheck size={21}/></span><h3>What happened?</h3><p>On November 16, malicious JavaScript was distributed through Optimizely code used by sites belonging to 178 organizations, according to Report URI.</p><div className="statline"><strong>178</strong><span>organizations identified</span></div><div className="statline"><strong>188</strong><span>infected scripts identified</span></div><a href={source} target="_blank" rel="noreferrer">Read the original investigation <ExternalLink size={14}/></a></div><div className="sidecard soft"><BookOpen size={20}/><h3>Know the limits</h3><p>Different websites had different exposure windows. Some legitimate site security policies may have blocked parts of the attack.</p><p>This app does not visit the websites you enter, request sensitive data, upload history, or run a device scan.</p></div><div className="sidecard tiny"><FileText size={18}/><h3>Source transparency</h3><p>Compiled November 18, 2026 from published research. Some additional subdomains are omitted from the original display, so the dataset is not exhaustive.</p><a href="https://pages.optimizely.com/rs/947-RKE-048/images/Security%20Incident%20Report%20-%20Optimizely%20Web%20Experimentation%20-%20Nov%2017%202026.pdf" target="_blank" rel="noreferrer">Optimizely incident report <ExternalLink size={14}/></a></div></aside></div>
  <footer>CyberCheck · Privacy-first exposure screening · No accounts, advertising scripts, or analytics. <span>Research last curated November 18, 2026.</span></footer></main></div>
}
createRoot(document.getElementById('root')).render(<App/>);
