import React, {useMemo, useState} from 'react';
import {createRoot} from 'react-dom/client';
import pptxgen from 'pptxgenjs';
import mammoth from 'mammoth';
import * as pdfjsLib from 'pdfjs-dist';
import pdfWorker from 'pdfjs-dist/build/pdf.worker.min.mjs?url';
import './style.css';
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfWorker;

const C={teal:'075766',red:'A1164F',navy:'24205F',cyan:'2CB8CE',gold:'F5C84C',paper:'F7F5F0',pale:'EDF5F6',ink:'263238',white:'FFFFFF'};
const initial=[
 {type:'title',title:'Real skills. Real support. Real careers.',body:'A practical introduction to person-centred support',sub:'H&H Accredited Training  •  Faculty teaching deck'},
 {type:'agenda',title:'Today’s learning journey',body:'Understand the foundations\nExplore practical approaches\nApply learning to real situations\nCheck understanding'},
 {type:'objectives',title:'By the end of this lesson, you can…',body:'Explain the key principles\nIdentify safe and effective practice\nApply the approach to a case study'},
 {type:'content',title:'Start with the person',body:'Good support begins by understanding the person, their preferences and what matters to them.\n\nListen actively and communicate clearly.\nRespect choice, dignity and independence.\nAdapt support to the individual.'},
 {type:'activity',title:'Put it into practice',body:'In pairs, review the scenario and identify two ways to support choice and independence.\n\nAllow 5 minutes, then share one insight with the group.'},
 {type:'summary',title:'The takeaways',body:'Person-centred support starts with listening.\nSmall choices build confidence and independence.\nSafe practice and dignity go hand in hand.'}
];
const layouts=[['title','Title slide'],['agenda','Lesson agenda'],['section','Section divider'],['objectives','Learning goals'],['content','Key points'],['summary','Quick summary'],['activity','Class activity'],['discussion','Discussion'],['quiz','Knowledge check'],['chart','Data / chart slide']];
function App(){
 const [file,setFile]=useState(null),[source,setSource]=useState(''),[slides,setSlides]=useState(initial),[mode,setMode]=useState('Lecture'),[course,setCourse]=useState('Certificate III in Individual Support'),[busy,setBusy]=useState(false),[active,setActive]=useState(0),[notice,setNotice]=useState('Drop a document to build your first draft.');
 const [brand,setBrand]=useState(true);
 const addSlide=(type)=>{const s={type,title:layouts.find(x=>x[0]===type)?.[1]||'New slide',body:type==='quiz'?'Question: Add your question here\n\nA. Option one\nB. Option two\nC. Option three\nD. Option four':type==='discussion'?'What would you do in this situation?\n\nConsider the person’s needs, preferences and safety.':'Add your teaching points here.'};setSlides(v=>[...v,s]);setActive(slides.length)};
 const update=(k,val)=>setSlides(v=>v.map((s,i)=>i===active?{...s,[k]:val}:s));
 async function readFile(f){setBusy(true);setFile(f);setNotice('Reading your material…');try{let text='';const ext=f.name.split('.').pop().toLowerCase();if(ext==='txt'||ext==='md')text=await f.text();else if(ext==='docx'){const r=await mammoth.extractRawText({arrayBuffer:await f.arrayBuffer()});text=r.value;}else if(ext==='pdf'){const pdf=await pdfjsLib.getDocument({data:await f.arrayBuffer()}).promise;for(let p=1;p<=pdf.numPages;p++){const page=await pdf.getPage(p);const c=await page.getTextContent();text+=c.items.map(x=>x.str).join(' ')+'\n';}}else if(ext==='pptx'){throw new Error('PPTX import is not enabled yet. Export the source as PDF or DOCX, then drop it here.');}else throw new Error('Please use PDF, DOCX, TXT or MD.');setSource(text);const generated=structure(text,mode);setSlides(generated.length?generated:initial);setActive(0);setNotice(`Imported ${f.name}. Review the slide outline, then export your deck.`);}catch(e){setNotice(e.message||'Could not read that file.')}finally{setBusy(false)}}
 function structure(text,kind){const clean=text.replace(/\r/g,'').split('\n').map(x=>x.trim()).filter(Boolean);const chunks=[];let cur=[];for(const line of clean){if((line.length<85&&(/[.!?]$/.test(line)===false||/^\d+[.)]/.test(line)))&&cur.length){chunks.push(cur.join('\n'));cur=[line]}else cur.push(line);if(cur.join(' ').length>650){chunks.push(cur.join('\n'));cur=[]}}if(cur.length)chunks.push(cur.join('\n'));const out=[];const heading=(clean.find(x=>x.length>5&&x.length<90)||'Teaching session').replace(/^[#\d.)\s-]+/,'');out.push({type:'title',title:heading,body:course,sub:'H&H Accredited Training'});if(kind!=='Quiz')out.push({type:'agenda',title:'Today’s learning journey',body:'Explore the core concepts\nConnect theory to practice\nApply learning through activities\nCheck understanding'});out.push({type:'objectives',title:'Learning goals',body:'Explain the main ideas in this topic\nApply the concepts to a practical situation\nReflect on safe and effective practice'});chunks.slice(0,12).forEach((chunk,i)=>{const lines=chunk.split('\n');let title=lines[0].replace(/^[#\d.)\s-]+/,'');if(title.length>72||title.split(' ').length>11)title=`Key teaching points ${i+1}`;let body=chunk===lines[0]?'Add supporting explanation and examples.':lines.slice(1).join('\n')||chunk;out.push({type:'content',title,body});});if(kind==='Quiz')out.push({type:'quiz',title:'Knowledge check',body:'Add a question to test understanding.\n\nA. Option one\nB. Option two\nC. Option three\nD. Option four'});else out.push({type:'activity',title:'Apply your learning',body:'Discuss a practical example with a partner. What would good practice look like?'});out.push({type:'summary',title:'Key takeaways',body:'What are the three most important ideas to remember?\nHow will you apply them in practice?'});return out}
 async function exportPptx(){setBusy(true);setNotice('Building your editable PowerPoint…');try{const pptx=new pptxgen();pptx.layout='LAYOUT_WIDE';pptx.author='H&H Accredited Training';pptx.subject='Faculty teaching presentation';pptx.title=slides[0]?.title||'H&H Teaching Slides';pptx.company='H&H Accredited Training';pptx.lang='en-AU';pptx.theme={headFontFace:'Manrope',bodyFontFace:'Source Sans 3',lang:'en-AU'};pptx.defineSlideMaster({title:'HH_BASE',background:{color:C.paper},objects:[{line:{x:0,y:7.32,w:13.333,h:0,line:{color:'D9E2E2',width:1}}},{text:{text:'H&H  |  ACCREDITED TRAINING',options:{x:.55,y:7.05,w:4,h:.18,fontFace:'Source Sans 3',fontSize:8,color:C.teal,bold:true,charSpacing:1}}},{text:{text:'REAL SKILLS. REAL SUPPORT. REAL CAREERS.',options:{x:8.25,y:7.05,w:4.5,h:.18,fontFace:'Source Sans 3',fontSize:7,color:'64757A',align:'right',charSpacing:.5}}}],slideNumber:{x:12.8,y:7.05,color:C.teal,fontFace:'Source Sans 3',fontSize:8}});
 for(let i=0;i<slides.length;i++){const s=slides[i],sl=pptx.addSlide('HH_BASE');sl.background={color:s.type==='title'?C.teal:C.paper};const dark=s.type==='title'||s.type==='section';const fg=dark?C.white:C.ink;const accent=dark?C.gold:C.red;
 if(s.type==='title'||s.type==='section'){sl.addShape(pptx.ShapeType.arc,{x:8.3,y:-.8,w:5.6,h:8.3,line:{color:C.cyan,width:3,transparency:5},adjustPoint:.2,rotate:5});sl.addShape(pptx.ShapeType.arc,{x:8.65,y:-.7,w:5.4,h:8.1,line:{color:C.red,width:2,transparency:5},rotate:5});sl.addText('h&h',{x:.7,y:.55,w:2.4,h:.72,fontFace:'Manrope',fontSize:40,bold:true,color:C.white,breakLine:false,margin:0});sl.addText('Accredited Training',{x:.78,y:1.27,w:2.5,h:.3,fontFace:'Source Sans 3',fontSize:15,color:C.white,margin:0});sl.addText(s.title,{x:.8,y:2.45,w:7.5,h:1.55,fontFace:'Manrope',fontSize:30,bold:true,color:C.white,breakLine:false,fit:'shrink',margin:0});sl.addText(s.body||'',{x:.82,y:4.25,w:6.6,h:1.2,fontFace:'Source Sans 3',fontSize:19,color:'EAF4F4',breakLine:false,fit:'shrink',margin:0});sl.addText(s.sub||course,{x:.82,y:6.45,w:6.3,h:.3,fontFace:'Source Sans 3',fontSize:11,color:C.gold,margin:0});}
 else {sl.addShape(pptx.ShapeType.rect,{x:0,y:0,w:.16,h:7.0,line:{color:C.teal,transparency:100},fill:{color:C.teal}});sl.addText(s.title,{x:.7,y:.55,w:11.8,h:.72,fontFace:'Manrope',fontSize:27,bold:true,color:C.teal,margin:0,fit:'shrink'});sl.addShape(pptx.ShapeType.line,{x:.72,y:1.42,w:1.2,h:0,line:{color:C.red,width:3}});
 if(s.type==='agenda'||s.type==='objectives'||s.type==='summary'){const items=s.body.split(/\n+/).filter(Boolean);items.forEach((t,j)=>{const y=1.9+j*.82;sl.addShape(pptx.ShapeType.ellipse,{x:.85,y:y+.1,w:.34,h:.34,line:{color:j%2?C.cyan:C.red,transparency:100},fill:{color:j%2?C.cyan:C.red}});sl.addText(t.replace(/^[-•\d.)\s]+/,''),{x:1.45,y:y,w:10.6,h:.55,fontFace:'Source Sans 3',fontSize:19,color:C.ink,breakLine:false,fit:'shrink',margin:0.03});});}
 else if(s.type==='quiz'){sl.addShape(pptx.ShapeType.roundRect,{x:.75,y:1.85,w:11.8,h:4.6,rectRadius:.12,line:{color:'DCE7E7',width:1},fill:{color:C.white}});sl.addText(s.body,{x:1.2,y:2.25,w:10.8,h:3.8,fontFace:'Source Sans 3',fontSize:21,color:C.ink,breakLine:false,fit:'shrink',margin:.08});sl.addText('CHECK YOUR UNDERSTANDING',{x:1.2,y:6.1,w:4,h:.2,fontFace:'Manrope',fontSize:9,bold:true,color:C.red,charSpacing:1});}
 else {sl.addShape(pptx.ShapeType.roundRect,{x:.75,y:1.85,w:11.8,h:4.75,rectRadius:.12,line:{color:'DCE7E7',width:1},fill:{color:C.white}});sl.addText(s.body,{x:1.15,y:2.2,w:s.imageData?6.1:10.9,h:4.0,fontFace:'Source Sans 3',fontSize:20,color:C.ink,breakLine:false,fit:'shrink',margin:.08});if(s.imageData){sl.addImage({data:s.imageData,x:7.65,y:2.2,w:4.45,h:3.8,});}if(s.type==='chart'){sl.addText('DATA STORY / INSERT YOUR MEASURES',{x:1.2,y:5.85,w:4,h:.2,fontFace:'Manrope',fontSize:8,bold:true,color:C.teal,charSpacing:1});[.48,.82,.62,.98].forEach((h,j)=>{sl.addShape(pptx.ShapeType.roundRect,{x:7.1+j*1.05,y:5.75-h*2,w:.58,h:h*2,rectRadius:.05,line:{color:[C.teal,C.cyan,C.red,C.gold][j],transparency:100},fill:{color:[C.teal,C.cyan,C.red,C.gold][j]}});});}if(s.resourceUrl){sl.addShape(pptx.ShapeType.roundRect,{x:1.15,y:6.0,w:3.8,h:.42,rectRadius:.06,line:{color:C.teal,width:1},fill:{color:C.pale}});sl.addText(s.resourceLabel||'OPEN CLASS RESOURCE',{x:1.3,y:6.13,w:3.4,h:.12,fontFace:'Manrope',fontSize:8,bold:true,color:C.teal,hyperlink:{url:s.resourceUrl},margin:0});}if(s.type==='activity'||s.type==='discussion'){sl.addShape(pptx.ShapeType.roundRect,{x:9.4,y:5.7,w:2.6,h:.5,rectRadius:.08,line:{color:C.teal,transparency:100},fill:{color:C.pale}});sl.addText(s.type==='activity'?'LEARN BY DOING':'SHARE YOUR THINKING',{x:9.52,y:5.86,w:2.35,h:.16,fontFace:'Manrope',fontSize:8,bold:true,color:C.teal,align:'center',margin:0});}}
 }
 }
 await pptx.writeFile({fileName:'HH-Accredited-Training-Teaching-Deck.pptx'});setNotice('PowerPoint exported. It is editable in Microsoft PowerPoint.');}catch(e){console.error(e);setNotice('Export failed: '+e.message)}finally{setBusy(false)}}
 const activeSlide=slides[active]||slides[0];
 return <div className="app"><aside className="sidebar"><div className="brand"><img src="/assets/hh-logo.png"/><span>SLIDE STUDIO</span></div><div className="side-label">WORKSPACE</div><button className="side-item selected">✦ <span>Presentation builder</span></button><a className="side-item" href="/how-to.html" style={{textDecoration:"none"}}>⌁ <span>Staff quick guide</span></a><button className="side-item" onClick={()=>setNotice('Brand system is locked to the supplied H&H guideline.')}>◈ <span>Brand system</span><b>LOCKED</b></button><div className="side-bottom"><div className="avatar">HH</div><div><strong>Faculty workspace</strong><small>H&H Accredited Training</small></div></div></aside>
 <main className="main"><header className="topbar"><div><div className="eyebrow">FACULTY TOOLKIT / POWERPOINT GENERATOR</div><h1>Teaching, beautifully presented.</h1><p>Turn your teaching material into a consistent, classroom-ready deck.</p></div><div className="top-actions"><span className="secure">● H&H BRAND APPLIED</span><button className="export" disabled={busy||!slides.length} onClick={exportPptx}>{busy?'Preparing…':'↓  Export PowerPoint'}</button></div></header>
 <section className="workspace"><div className="left-panel"><div className="panel-head"><div><span className="step">01 / SOURCE MATERIAL</span><h2>Start with your content</h2><p>Drop in lecture notes, a course guide or a worksheet.</p></div><span className="file-icon">↥</span></div><label className="dropzone" onDragOver={e=>e.preventDefault()} onDrop={e=>{e.preventDefault();if(e.dataTransfer.files[0])readFile(e.dataTransfer.files[0])}}><input type="file" accept=".pdf,.docx,.txt,.md" onChange={e=>e.target.files[0]&&readFile(e.target.files[0])}/><span className="upload-icon">↑</span><strong>{file?file.name:'Drop your material here'}</strong><span>or <u>browse files</u> from your computer</span><small>PDF · DOCX · TXT · MD</small></label><div className="or-line"><span>DECK SETTINGS</span></div><label className="field-label">Teaching format</label><div className="mode-switch">{['Lecture','Quiz','Workshop'].map(x=><button className={mode===x?'active':''} onClick={()=>setMode(x)}>{x}</button>)}</div><label className="field-label">Course / unit name</label><input className="text-input" value={course} onChange={e=>setCourse(e.target.value)}/><div className="brand-note"><span>✦</span><div><strong>H&H design system is active</strong><small>Approved palette, typography, spacing and footer are applied automatically.</small></div></div><button className="build-btn" disabled={!source||busy} onClick={()=>{setSlides(structure(source,mode));setActive(0);setNotice('Your content has been reorganised into a teaching deck. Review each slide before export.')}}>✦  Build slide outline</button></div>
 <div className="right-panel"><div className="panel-head right-head"><div><span className="step">02 / DECK EDITOR</span><h2>Your teaching deck</h2><p>Review and refine the slide content before export.</p></div><span className="slide-count">{slides.length} SLIDES</span></div><div className="editor"><div className="slide-list">{slides.map((s,i)=><button className={`slide-thumb ${active===i?'current':''}`} onClick={()=>setActive(i)}><span className="thumb-no">{String(i+1).padStart(2,'0')}</span><span className="thumb-title">{s.title}</span><span className="thumb-type">{layouts.find(x=>x[0]===s.type)?.[1]||'Content'}</span></button>)}<button className="add-slide" onClick={()=>addSlide('content')}>＋ Add slide</button></div><div className="edit-area">{activeSlide&&<><div className="preview-wrap"><div className={`mini-slide ${['title','section'].includes(activeSlide.type)?'dark':''}`}><div className="mini-logo">h<span>&</span>h <small>Accredited Training</small></div><div className="mini-rule"></div><h3>{activeSlide.title}</h3><p>{activeSlide.body.split('\n').filter(Boolean).slice(0,4).join('  •  ')}</p><div className="mini-footer">REAL SKILLS. REAL SUPPORT. REAL CAREERS.</div></div></div><div className="edit-fields"><div className="edit-head"><span>EDIT SELECTED SLIDE</span><select value={activeSlide.type} onChange={e=>update('type',e.target.value)}>{layouts.map(([v,l])=><option value={v}>{l}</option>)}</select></div><label>Slide heading</label><input value={activeSlide.title} onChange={e=>update('title',e.target.value)}/><label>Teaching content</label><textarea rows="7" value={activeSlide.body} onChange={e=>update('body',e.target.value)} placeholder="Add text, bullet points or questions…"/><label>Slide image (optional)</label><input type="file" accept="image/png,image/jpeg" onChange={e=>{const f=e.target.files?.[0];if(f){const r=new FileReader();r.onload=()=>update('imageData',r.result);r.readAsDataURL(f)}}}/>{activeSlide.imageData&&<button className="delete-slide" onClick={()=>update('imageData',null)}>Remove image</button>}<label>Video / worksheet link (optional)</label><input value={activeSlide.resourceUrl||''} onChange={e=>update('resourceUrl',e.target.value)} placeholder="https://…"/><div className="field-hint">Tip: Put each bullet or answer option on a new line. Add a photo to create a balanced text-and-image slide. The exported slide remains editable.</div><button className="delete-slide" onClick={()=>{if(slides.length>1){setSlides(v=>v.filter((_,i)=>i!==active));setActive(Math.max(0,active-1))}}}>Remove slide</button></div></>}</div></div></div></div>
 <div className="bottom-row"><div className="bottom-card"><span className="bottom-symbol">▧</span><div><strong>Designed for teaching</strong><small>Title, agenda, goals, content, activities, discussion, quiz and summary layouts.</small></div></div><div className="bottom-card"><span className="bottom-symbol">◉</span><div><strong>One consistent identity</strong><small>H&H colours, Manrope headings, Source Sans 3 body text and branded slide furniture.</small></div></div><div className="bottom-card"><span className="bottom-symbol">↗</span><div><strong>PowerPoint-ready</strong><small>Editable text and shapes, widescreen 16:9 format, reusable master layout and theme.</small></div></div></div>
 <footer className="status"><span className="status-dot"></span>{notice}<span className="status-right">H&H ACCREDITED TRAINING · SYDNEY</span></footer></main></div>
}
createRoot(document.getElementById('root')).render(<App/>);
