// ─── API CALLS ───────────────────────────────────────────────── const callAPI = async (prompt) => { const res = await fetch(WORKER_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt }), }); const rawText = await res.text(); if (!rawText) throw new Error("empty"); let data; try { data = JSON.parse(rawText); } catch(e) { throw new Error(rawText.substring(0, 100)); } if (data.error) throw new Error(JSON.stringify(data.error).substring(0, 150)); if (!data.content) throw new Error("no content"); const text = data.content.map(i => i.text || "").join(""); const clean = text.replace(/```json\s*/g, "").replace(/```\s*/g, "").trim(); const m = clean.match(/\{[\s\S]*\}/); if (!m) throw new Error("no JSON"); return JSON.parse(m[0]); }; const ctx = () => { const f = state.form; const country = COUNTRIES.find(x => x.id === f.country)?.label; const industry = INDUSTRIES.find(x => x.id === f.industry)?.label; const stage = STAGES.find(x => x.id === f.stage)?.label; const gender = GENDERS.find(x => x.id === f.targetGender)?.label; const bizType = BUSINESS_TYPES.find(x => x.id === f.businessType)?.label; const goal = GOALS.find(x => x.id === f.goal)?.label; const plats = f.platforms.map(p => PLATFORMS.find(x => x.id === p)?.label).join(", "); const budget = BUDGETS.find(x => x.id === f.budget)?.label; const duration = DURATIONS.find(x => x.id === f.duration)?.label; const location = f.targetWholeCountry ? country : `${f.region}, ${country}`; return `المشروع: ${f.offerName} | المجال: ${industry} | الدولة: ${location} | السعر: ${f.price} | الهدف: ${goal} | المنصات: ${plats} | الميزانية: ${budget} | الجنس: ${gender} | الأعمار: ${f.targetAges.join(",")} | نوع: ${bizType} | المرحلة: ${stage}${f.competitors ? ` | منافسون: ${f.competitors}` : ""} | الوصف: ${f.offerDesc} | فترة الخطة: ${duration} | الدولة المستهدفة: ${country}`; }; const prompt1 = () => `أنت DMF System - محمود شعبان. ${ctx()} JSON فقط بدون أي نص: {"warnings":[],"strategy":{"positioningStatement":"","brandVsSales":"","usp":"","valueProposition":"","marketAnalysis":"","swot":{"strengths":[""],"weaknesses":[""],"opportunities":[""],"threats":[""]}},"audience":{"primaryPersona":{"name":"","age":"","gender":"","income":"","interests":[""],"painPoints":[""],"goals":[""],"objections":[""],"platforms":""},"secondaryPersona":"","metaTargeting":{"interests":[""],"behaviors":[""],"exclusions":[""],"lookalike":""},"tiktokTargeting":""}}`; const prompt2 = () => `أنت DMF System - محمود شعبان. ${ctx()} JSON فقط بدون نص. المنافسون أسماء حقيقية فعلاً في السوق: {"competitors":[{"name":"","size":"","strengths":[""],"weaknesses":[""],"pricing":"","marketingStrategy":"","howToBeat":""}],"mediaBuying":{"budgetAllocation":"","testingBudget":"","scalingStrategy":"","platformPlans":[{"platform":"","campaignObjective":"","campaignStructure":"","biddingStrategy":"","targetingDetails":"","creativeFormats":"","abTestPlan":"","kpis":[""],"monthlyBudget":"","expectedResults":"","commonMistakes":[""]}]}}`; const prompt3 = () => `أنت DMF System - محمود شعبان. ${ctx()} JSON فقط بدون نص. عدد phases يناسب فترة الخطة: {"content":{"creativeDirection":"","contentPillars":["","","",""],"postingFrequency":"","monthlyPostDistribution":"","videoIdeas":[{"title":"","format":"","duration":"","platform":"","purpose":"","script":""}],"contentCalendar":""},"hooks":[{"type":"","text":"","platform":"","funnel":"","emotion":""}],"salesFunnel":{"stage1_traffic":{"title":"Stage 1: Traffic","description":"","platforms":"","creatives":"","budget":""},"stage2_landing":{"title":"Stage 2: Landing","description":"","structure":"","cta":"","elements":[""]},"stage3_lead":{"title":"Stage 3: Lead","description":"","leadMagnet":"","form":""},"stage4_email":{"title":"Stage 4: Email","description":"","emails":[""]},"stage5_sales":{"title":"Stage 5: Sales","description":"","tactics":[""],"objectionHandling":""},"stage6_retention":{"title":"Stage 6: Retention","description":"","tactics":[""]}},"customerJourney":{"awareness":{"stage":"Awareness","customerEmotion":"","touchpoints":[""],"yourAction":"","content":""},"consideration":{"stage":"Consideration","customerEmotion":"","touchpoints":[""],"yourAction":"","content":""},"decision":{"stage":"Decision","customerEmotion":"","touchpoints":[""],"yourAction":"","content":""},"purchase":{"stage":"Purchase","customerEmotion":"","touchpoints":[""],"yourAction":"","content":""},"loyalty":{"stage":"Loyalty","customerEmotion":"","touchpoints":[""],"yourAction":"","content":""}},"actionPlan":{"phases":[{"title":"","duration":"","objective":"","actions":[""],"budget":"","deliverables":[""],"kpis":[""]}],"weeklyCheckIns":"","monthlyReports":"","successCriteria":[""]}}`; const run = async () => { state.screen = "loading"; state.progress = 5; state.error = ""; render(); const iv = setInterval(() => { if (state.progress < 88) { state.progress += Math.random() * 3; render(); } }, 800); try { // Run 3 calls in PARALLEL - much faster! const [p1, p2, p3] = await Promise.all([ callAPI(prompt1()), callAPI(prompt2()), callAPI(prompt3()), ]); clearInterval(iv); state.progress = 96; render(); state.results = { ...p1, ...p2, ...p3 }; state.progress = 100; render(); setTimeout(() => { state.screen = "results"; state.activeTab = "strategy"; render(); }, 400); } catch (e) { clearInterval(iv); state.error = "خطأ: " + e.message; state.screen = "wizard"; render(); } }; // ─── HELPERS ─────────────────────────────────────────────────── const esc = (s) => String(s || "").replace(/[&<>"']/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); const renderList = (items) => { if (!items || !Array.isArray(items)) return ""; return items.map(item => `
${esc(item)}
`).join(""); }; // ─── STEP RENDERERS ──────────────────────────────────────────── const stepCountry = () => { const f = state.form; const country = COUNTRIES.find(c => c.id === f.country); return `

🌍 إيه الدولة المستهدفة؟

الاستراتيجية هتكون مخصصة للسوق المحلي

${COUNTRIES.map(c => `
${c.icon}
${c.label}
`).join("")}
${country ? `
${!f.targetWholeCountry ? ` ` : ""}
` : ""} `; }; const stepIndustry = () => { const f = state.form; return `

🏭 إيه المجال؟

الاختيار ده بيأثر على كل التوصيات

${INDUSTRIES.map(i => `
${i.icon}
${i.label}
`).join("")}
`; }; const stepOffer = () => { const f = state.form; return `

📦 بيانات العرض

عرّفنا بمنتجك أو خدمتك

💡السيستم هيكشف العيوب والفرص تلقائياً — مش محتاج تكتبها
`; }; const stepAudience = () => { const f = state.form; return `

👥 الجمهور المستهدف

حدد جمهورك بدقة عشان نوصل لـ Targeting أفضل

${GENDERS.map(g => `
${g.icon}
${g.label}
`).join("")}
${AGES.map(a => `
${a.label}
`).join("")}
${BUSINESS_TYPES.map(b => `
${b.icon}
${b.label}
${b.desc}
`).join("")} `; }; const stepCompetitors = () => { const f = state.form; return `

🥊 المنافسون والمرحلة

معلومات إضافية تساعد في التحليل

${STAGES.map(s => `
${s.icon} ${s.label}
`).join("")} `; }; const stepResources = () => { const f = state.form; const yesNo = [{id: "yes", label: "آه"}, {id: "no", label: "لأ"}]; return `

🛠️ الموارد المتاحة

عشان نبني خطة واقعية بناءاً على إمكانياتك

${yesNo.map(y => `
${y.label}
`).join("")}
لوحدي
عندي فريق
${yesNo.map(y => `
${y.label}
`).join("")}
`; }; const stepGoal = () => { const f = state.form; return `

🎯 إيه هدفك؟

ده بيحدد طبيعة الاستراتيجية كلها

${GOALS.map(g => `
${g.icon}
${g.label}
${g.desc}
`).join("")}
`; }; const stepPlatforms = () => { const f = state.form; return `

📱 إيه المنصات؟

ممكن تختار أكتر من منصة

${PLATFORMS.map(p => `
${p.icon} ${p.label} ${f.platforms.includes(p.id) ? `` : ""}
`).join("")} `; }; const stepBudget = () => { const f = state.form; return `

💰 الميزانية الشهرية

بيأثر على هيكل الحملات والـ Scaling

${BUDGETS.map(b => `
💰 ${b.label}
`).join("")}
`; }; const stepDuration = () => { const f = state.form; return `

⏰ فترة الخطة

قد إيه الخطة هتغطي

${DURATIONS.map(d => `
${d.icon}
${d.label}
${d.desc}
`).join("")} `; }; const stepRenderers = [stepCountry, stepIndustry, stepOffer, stepAudience, stepCompetitors, stepResources, stepGoal, stepPlatforms, stepBudget, stepDuration]; // ─── RESULTS RENDERERS ───────────────────────────────────────── const renderStrategy = () => { const r = state.results; if (!r) return ""; const s = r.strategy || {}; return ` ${r.warnings && r.warnings.length > 0 ? `
⚠️ ملاحظات مهمة
${r.warnings.map(w => `
• ${esc(w)}
`).join("")}
` : ""}
📍 Positioning Statement
${esc(s.positioningStatement)}
👑 Brand vs Sales — التحليل
${esc(s.brandVsSales)}
💎 USP
${esc(s.usp)}
💡 Value Proposition
${esc(s.valueProposition)}
📊 تحليل السوق
${esc(s.marketAnalysis)}
${[ { label: "💪 Strengths", items: s.swot?.strengths, color: "#22c55e" }, { label: "😓 Weaknesses", items: s.swot?.weaknesses, color: "#ef4444" }, { label: "🌟 Opportunities", items: s.swot?.opportunities, color: "#f59e0b" }, { label: "⚡ Threats", items: s.swot?.threats, color: "#8b5cf6" }, ].map(({ label, items, color }) => `
${label}
${(items || []).map(x => `
• ${esc(x)}
`).join("")}
`).join("")}
`; }; const renderAudience = () => { const r = state.results; if (!r) return ""; const a = r.audience || {}; const p = a.primaryPersona || {}; return `
👤 Primary Persona
${[ { label: "الاسم", val: p.name }, { label: "العمر", val: p.age }, { label: "الجنس", val: p.gender }, { label: "الدخل", val: p.income }, ].map(({ label, val }) => `
${label}
${esc(val)}
`).join("")}
🎯 الاهتمامات
${(p.interests || []).map(i => `${esc(i)}`).join("")}
😰 Pain Points
${renderList(p.painPoints)}
🎯 الأهداف
${renderList(p.goals)}
🚫 الاعتراضات المحتملة
${renderList(p.objections)}
📱 المنصات
${esc(p.platforms)}
👥 Secondary Persona
${esc(a.secondaryPersona)}
${a.metaTargeting ? `
📘 Meta Targeting
الاهتمامات
${(a.metaTargeting.interests || []).map(i => `${esc(i)}`).join("")}
السلوكيات
${(a.metaTargeting.behaviors || []).map(i => `${esc(i)}`).join("")}
⛔ Exclusions
${(a.metaTargeting.exclusions || []).map(i => `${esc(i)}`).join("")}
💡 Lookalike
${esc(a.metaTargeting.lookalike)}
` : ""} ${a.tiktokTargeting ? `
🎵 TikTok Targeting
${esc(a.tiktokTargeting)}
` : ""} `; }; const renderCompetitors = () => { const r = state.results; if (!r || !r.competitors) return ""; return r.competitors.map((c, i) => `
🏢 ${esc(c.name)} — ${esc(c.size)}
💪 نقاط القوة
${renderList(c.strengths)}
😓 نقاط الضعف
${renderList(c.weaknesses)}
💰 استراتيجية التسعير
${esc(c.pricing)}
📣 الاستراتيجية التسويقية
${esc(c.marketingStrategy)}
🏆 إزاي تتفوق عليه
${esc(c.howToBeat)}
`).join(""); }; const renderMedia = () => { const r = state.results; if (!r || !r.mediaBuying) return ""; const m = r.mediaBuying; return `
💰 توزيع الميزانية
${esc(m.budgetAllocation)}
Testing Budget
${esc(m.testingBudget)}
Scaling Strategy
${esc(m.scalingStrategy)}
${(m.platformPlans || []).map(p => `
${esc(p.platform)}
${[ { label: "🎯 Campaign Objective", val: p.campaignObjective }, { label: "🏗️ Campaign Structure", val: p.campaignStructure }, { label: "💵 Bidding Strategy", val: p.biddingStrategy }, { label: "👥 Targeting", val: p.targetingDetails }, { label: "🎨 Creative Formats", val: p.creativeFormats }, { label: "🔬 A/B Test Plan", val: p.abTestPlan }, { label: "📈 Expected Results", val: p.expectedResults }, { label: "💰 Monthly Budget", val: p.monthlyBudget }, ].map(({ label, val }) => `
${label}
${esc(val)}
`).join("")}
📊 KPIs المستهدفة
${(p.kpis || []).map(k => `${esc(k)}`).join("")}
${p.commonMistakes && p.commonMistakes.length > 0 ? `
⚠️ أغلاط شائعة
${p.commonMistakes.map(x => `
• ${esc(x)}
`).join("")}
` : ""}
`).join("")} `; }; const renderContent = () => { const r = state.results; if (!r || !r.content) return ""; const c = r.content; return `
🎨 Creative Direction
${esc(c.creativeDirection)}
🏛️ Content Pillars
${renderList(c.contentPillars)}
📅 Posting Frequency
${esc(c.postingFrequency)}
📋 توزيع البوستات الشهري
${esc(c.monthlyPostDistribution)}
🎬 أفكار الفيديو
${(c.videoIdeas || []).map((v, i) => `
${esc(v.title)}
${esc(v.format)} ${esc(v.duration)} ${esc(v.platform)} ${esc(v.purpose)}
📝 ${esc(v.script)}
`).join("")}
📆 Content Calendar
${esc(c.contentCalendar)}
`; }; const renderHooks = () => { const r = state.results; if (!r || !r.hooks) return ""; return r.hooks.map((h, i) => `
هوك #${i + 1}
"${esc(h.text)}"
${esc(h.type)} ${esc(h.platform)} ${esc(h.funnel)} ${esc(h.emotion)}
`).join(""); }; const renderFunnel = () => { const r = state.results; if (!r || !r.salesFunnel) return ""; const sf = r.salesFunnel; const stages = [ { key: "stage1_traffic", color: "#f59e0b" }, { key: "stage2_landing", color: "#38bdf8" }, { key: "stage3_lead", color: "#a855f7" }, { key: "stage4_email", color: "#ec4899" }, { key: "stage5_sales", color: "#22c55e" }, { key: "stage6_retention", color: "#f43f5e" }, ]; return stages.map(({ key, color }) => { const s = sf[key]; if (!s) return ""; return `
${esc(s.title)}
${esc(s.description)}
${s.platforms ? `
المنصات: ${esc(s.platforms)}
` : ""} ${s.creatives ? `
الإعلانات: ${esc(s.creatives)}
` : ""} ${s.budget ? `
الميزانية: ${esc(s.budget)}
` : ""} ${s.structure ? `
هيكل الصفحة:
${esc(s.structure)}
` : ""} ${s.cta ? `
CTA: ${esc(s.cta)}
` : ""} ${s.elements ? `
العناصر:
${renderList(s.elements)}
` : ""} ${s.leadMagnet ? `
Lead Magnet: ${esc(s.leadMagnet)}
` : ""} ${s.form ? `
الفورم: ${esc(s.form)}
` : ""} ${s.emails ? `
سلسلة الإيميلات:
${renderList(s.emails)}
` : ""} ${s.tactics ? `
التكتيكات:
${renderList(s.tactics)}
` : ""} ${s.objectionHandling ? `
التعامل مع الاعتراضات: ${esc(s.objectionHandling)}
` : ""}
`; }).join(""); }; const renderJourney = () => { const r = state.results; if (!r || !r.customerJourney) return ""; const cj = r.customerJourney; const stages = ["awareness", "consideration", "decision", "purchase", "loyalty"]; const colors = ["#f59e0b", "#38bdf8", "#a855f7", "#22c55e", "#f43f5e"]; return stages.map((k, i) => { const s = cj[k]; if (!s) return ""; return `
${i + 1}. ${esc(s.stage)}
😊 إيه اللي بيحسه العميل
${esc(s.customerEmotion)}
📍 نقاط الاتصال
${renderList(s.touchpoints)}
🎯 إيه تعمل
${esc(s.yourAction)}
📝 نوع المحتوى
${esc(s.content)}
`; }).join(""); }; const renderPlan = () => { const r = state.results; if (!r || !r.actionPlan) return ""; const p = r.actionPlan; return ` ${(p.phases || []).map((ph, i) => `
${esc(ph.duration)}
${esc(ph.title)}
${esc(ph.budget)}
🎯 الهدف
${esc(ph.objective)}
📋 الخطوات
${renderList(ph.actions)}
📦 المخرجات
${renderList(ph.deliverables)}
📊 KPIs
${(ph.kpis || []).map(k => `${esc(k)}`).join("")}
`).join("")}
📅 Weekly Check-ins
${esc(p.weeklyCheckIns)}
📆 Monthly Reports
${esc(p.monthlyReports)}
✅ معايير النجاح
${renderList(p.successCriteria)}
`; }; const tabRenderers = { strategy: renderStrategy, audience: renderAudience, competitors: renderCompetitors, media: renderMedia, content: renderContent, hooks: renderHooks, funnel: renderFunnel, journey: renderJourney, plan: renderPlan, }; // ─── MAIN RENDER ─────────────────────────────────────────────── const render = () => { const app = document.getElementById("app"); if (state.screen === "loading") { const msgs = [ "تحليل بيانات العرض...", "تحديد الجمهور المستهدف بدقة...", "البحث عن المنافسين الحقيقيين...", "بناء استراتيجية الـ Media Buying...", "تحديد الـ Targeting المثالي...", "توليد الهوكات الإعلانية...", "بناء Sales Funnel كامل...", "رسم Customer Journey Map...", "إعداد خطة العمل التفصيلية..." ]; const ci = Math.min(Math.floor(state.progress / 11), msgs.length - 1); app.innerHTML = `
DMF System شغّال...
${msgs[ci]}
${Math.round(state.progress)}%
مقدم من محمود شعبان
`; return; } if (state.screen === "results") { const country = COUNTRIES.find(c => c.id === state.form.country); const industry = INDUSTRIES.find(i => i.id === state.form.industry); app.innerHTML = `

${RESULT_TABS.find(t => t.id === state.activeTab)?.icon} ${RESULT_TABS.find(t => t.id === state.activeTab)?.label}

${tabRenderers[state.activeTab]()}
`; return; } // Wizard app.innerHTML = `
DMF SYSTEM
Marketing Strategy Builder
مقدم من محمود شعبان
${STEP_LABELS.map((label, i) => `
${i < state.step ? "✓" : i + 1}
${label}
`).join("")}
${state.error ? `
${esc(state.error)}
` : ""}
${stepRenderers[state.step]()}
${state.step > 0 ? `` : ""} ${state.step < 9 ? ` ` : ` `}
`; }; // ─── EXPORT FUNCTIONS ────────────────────────────────────────── window.selectCountry = (id) => { state.form.country = id; state.form.region = ""; render(); }; window.setWhole = (v) => { state.form.targetWholeCountry = v; if (v) state.form.region = ""; render(); }; window.selectRegion = (r) => { state.form.region = r; render(); }; window.selectIndustry = (id) => { state.form.industry = id; render(); }; window.setField = (k, v) => { state.form[k] = v; render(); }; window.setFieldNoRender = (k, v) => { state.form[k] = v; }; window.toggleField = (k, v) => toggle(k, v); window.next = next; window.back = back; window.run = run; window.goTab = goTab; window.reset = reset; window.refreshNav = () => { // Only update the action buttons without re-rendering the whole form const actions = document.querySelector('.actions'); if (!actions) return; const canN = canNext(); if (state.step < 9) { actions.innerHTML = ` ${state.step > 0 ? `` : ""} `; } else { actions.innerHTML = ` ${state.step > 0 ? `` : ""} `; } }; // Initial render render();